import React, { useEffect, useState } from 'react';
import api from '../services/api';
import { Button } from '../components/Button';
import { Plus, Pencil, Trash2, Box, Search } from 'lucide-react';
import { MobileList } from '../components/MobileList';
import { CreatePartModal } from '../components/modals/CreatePartModal';
import type { Part, GeometryType } from '../types';

export const PartsList: React.FC = () => {
    const [parts, setParts] = useState<Part[]>([]);
    const [loading, setLoading] = useState(true);
    const [editItem, setEditItem] = useState<Part | undefined>(undefined);
    const [geometryTypes, setGeometryTypes] = useState<GeometryType[]>([]);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');

    useEffect(() => {
        fetchParts();
        fetchGeometryTypes();
    }, []);

    const fetchParts = async () => {
        try {
            const response = await api.get('/parts');
            setParts(response.data);
        } catch (error) {
            console.error('Error fetching parts:', error);
        } finally {
            setLoading(false);
        }
    };

    const fetchGeometryTypes = async () => {
        try {
            const response = await api.get('/geometry-types');
            setGeometryTypes(response.data);
        } catch (error) {
            console.error('Error fetching geometry types:', error);
        }
    };

    const handleDelete = async (id: string) => {
        if (!window.confirm('Tem certeza que deseja excluir esta peça?')) return;
        try {
            await api.delete(`/parts/${id}`);
            fetchParts();
        } catch (error) {
            console.error('Error deleting part', error);
        }
    };

    const getLossForType = (type?: string) => {
        if (!type) return '--';
        const geo = geometryTypes.find(g => g.name === type);
        return geo ? `${geo.efficiencyLoss}%` : '--';
    };

    const filteredParts = parts.filter(p =>
        p.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
        (p.type && p.type.toLowerCase().includes(searchTerm.toLowerCase()))
    );

    const columns = [
        {
            header: 'Peça / Descrição',
            accessor: (p: Part) => (
                <div className="flex flex-col">
                    <span className="font-bold text-text-main text-xs uppercase tracking-tight">{p.description}</span>
                    <span className="text-[10px] text-text-muted font-medium uppercase">{p.type || 'Sem Categoria'}</span>
                </div>
            )
        },
        {
            header: 'Perdas Estim.(%)',
            accessor: (p: Part) => (
                <span className="text-orange-500 font-black text-xs">{getLossForType(p.type)}</span>
            )
        },
        {
            header: 'Peso (Kg)',
            accessor: (p: Part) => (
                <span className="text-text-main font-bold text-xs">{p.weight ? `${p.weight} kg` : '--'}</span>
            )
        },
        {
            header: 'Área (m²)',
            accessor: (p: Part) => (
                <span className="text-primary font-black text-xs">{p.area ? `${p.area} m²` : '--'}</span>
            )
        },
    ];

    if (loading) {
        return (
            <div className="flex justify-center items-center h-64">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
            </div>
        );
    }

    return (
        <div className="space-y-10 animate-in fade-in duration-700">
            {/* Page Header */}
            <div className="flex flex-col md:flex-row md:items-end justify-between gap-6 pb-2">
                <div className="space-y-2">
                    <div className="flex items-center gap-4">
                        <div className="w-14 h-14 rounded-2xl bg-primary/10 flex items-center justify-center text-primary shadow-lg shadow-primary/5">
                            <Box className="w-8 h-8" />
                        </div>
                        <div>
                            <h1 className="text-3xl md:text-5xl font-black text-text-main tracking-tight mb-0">Peças & Geometria</h1>
                            <p className="text-sm text-text-muted font-medium tracking-widest uppercase text-xs">Catálogo global de itens cadastrados</p>
                        </div>
                    </div>
                </div>

                <div className="flex gap-4">
                    <div className="relative hidden lg:block group">
                        <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted group-focus-within:text-primary transition-colors" />
                        <input
                            type="text"
                            placeholder="Buscar peças..."
                            className="h-14 w-64 bg-surface border border-border/40 rounded-2xl pl-12 pr-4 text-sm focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all font-medium shadow-sm"
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                        />
                    </div>
                    <Button onClick={() => { setEditItem(undefined); setIsModalOpen(true); }} size="lg" className="shadow-primary/30 h-14">
                        <Plus className="w-5 h-5 mr-2" />
                        Nova Peça
                    </Button>
                </div>
            </div>

            <div className="bg-surface rounded-[32px] border border-border/40 shadow-soft p-2">
                <MobileList
                    data={filteredParts}
                    columns={columns}
                    keyExtractor={(item) => item.id}
                    titleAccessor="description"
                    subtitleAccessor={(item) => `${item.type || 'N/A'} - ${item.weight || 0}kg`}
                    actionRender={(item) => (
                        <div className="flex gap-1 justify-end">
                            <button
                                onClick={() => { setEditItem(item); setIsModalOpen(true); }}
                                className="p-2 text-text-muted hover:text-primary hover:bg-primary/5 rounded-xl transition-all"
                                aria-label="Editar peça"
                                title="Editar peça"
                            >
                                <Pencil size={18} />
                            </button>
                            <button
                                onClick={() => handleDelete(item.id)}
                                className="p-2 text-text-muted hover:text-error hover:bg-error/5 rounded-xl transition-all"
                                aria-label="Excluir peça"
                                title="Excluir peça"
                            >
                                <Trash2 size={18} />
                            </button>
                        </div>
                    )}
                />

                {filteredParts.length === 0 && (
                    <div className="text-center py-24">
                        <div className="mx-auto h-20 w-20 bg-surface-soft rounded-full flex items-center justify-center text-text-muted/20 mb-6 border border-border/20">
                            <Box className="w-10 h-10" />
                        </div>
                        <h3 className="text-xl font-bold text-text-main">Nenhuma peça encontrada</h3>
                        <p className="mt-2 text-text-muted font-medium">Você ainda não possui peças cadastradas no sistema.</p>
                    </div>
                )}
            </div>

            <CreatePartModal
                isOpen={isModalOpen}
                onClose={() => { setIsModalOpen(false); setEditItem(undefined); }}
                onSuccess={fetchParts}
                initialData={editItem}
            />
        </div>
    );
};

