import React, { useEffect, useState } from 'react';
import api from '../services/api';
import { Button } from '../components/Button';
import { Plus, Pencil, Trash2, ClipboardCheck, Search, Paintbrush, Hammer, Camera } from 'lucide-react';
import { MobileList } from '../components/MobileList';
import { CreateInspectionModal } from '../components/modals/CreateInspectionModal';
import { format } from 'date-fns';
import type { Inspection, Project } from '../types';
import { clsx } from 'clsx';


export const InspectionsList: React.FC = () => {
    const [inspections, setInspections] = useState<Inspection[]>([]);
    const [projects, setProjects] = useState<Project[]>([]);
    const [loading, setLoading] = useState(true);
    const [editItem, setEditItem] = useState<Inspection | undefined>(undefined);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');

    useEffect(() => {
        fetchData();
    }, []);

    const fetchData = async () => {
        setLoading(true);
        try {
            // Fetch inspections
            try {
                const response = await api.get('/inspections');
                console.log('Inspeções carregadas do banco:', response.data);
                setInspections(response.data);
            } catch (error) {
                console.error('Error fetching inspections:', error);
            }

            // Fetch projects for lookup
            try {
                const projRes = await api.get('/projects');
                setProjects(projRes.data);
            } catch (error) {
                console.error('Error fetching projects:', error);
            }
        } finally {
            setLoading(false);
        }
    };

    const fetchInspections = fetchData; // Alias for compatibility with existing calls

    const handleDelete = async (id: string) => {
        if (!window.confirm('Tem certeza que deseja excluir esta inspeção?')) return;
        try {
            await api.delete(`/inspections/${id}`);
            fetchData();
        } catch (error) {
            console.error('Error deleting inspection', error);
        }
    };

    const filteredInspections = inspections.filter(i => {
        const project = projects.find(p => p.id === i.projectId);
        const projectName = project?.name?.toLowerCase() || '';
        const clientName = project?.client?.toLowerCase() || '';
        const search = searchTerm.toLowerCase();

        return (
            (i.inspector && i.inspector.toLowerCase().includes(search)) ||
            (i.pieceDescription && i.pieceDescription.toLowerCase().includes(search)) ||
            (i.defects && i.defects.toLowerCase().includes(search)) ||
            (i.type === 'surface_treatment' && i.batch?.toLowerCase().includes(search)) ||
            projectName.includes(search) ||
            clientName.includes(search)
        );
    });

    const getStatusIndicator = (targetType: 'painting' | 'surface_treatment', currentItem: Inspection) => {
        const normalize = (s: string | undefined | null) =>
            (s || '').normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim();

        const getPid = (p: string | { _id?: string; id?: string } | null | undefined): string => {
            if (!p) return '';
            if (typeof p === 'string') return p;
            const obj = p as { _id?: string; id?: string };
            return obj._id || obj.id || String(p);
        };

        const tProj = getPid(currentItem.projectId);
        const tDesc = normalize(currentItem.pieceDescription);
        const tBatch = normalize(currentItem.batch);

        const matches = inspections.filter(ins => {
            const iProj = getPid(ins.projectId);
            const iType = ins.type || 'painting';
            if (iProj !== tProj || iType !== targetType) return false;
            const iDesc = normalize(ins.pieceDescription);
            const iBatch = normalize(ins.batch);
            return (tDesc !== '' && (tDesc === iDesc || tDesc === iBatch)) ||
                (tBatch !== '' && (tBatch === iDesc || tBatch === iBatch));
        });

        // DEBUG AVANÇADO: Só logamos quando falha em achar uma peça que deveria existir
        if (matches.length === 0 && (tDesc.includes('perfis') || tDesc.includes('chapas'))) {
            const inSameProject = inspections.filter(ins => getPid(ins.projectId) === tProj);
            const otherStages = inSameProject.filter(ins => (ins.type || 'painting') === targetType);

            if (otherStages.length > 0) {
                console.group(`Diagnóstico de Falha: ${targetType} para "${tDesc}"`);
                console.log("Peça atual:", { desc: tDesc, lote: tBatch, proj: tProj });
                console.log(`Encontrei ${otherStages.length} registros de ${targetType} no projeto, mas nenhum casou com a descrição/lote.`);
                console.log("Dados dos registros ignorados para conferência:", otherStages.map(v => ({ desc: v.pieceDescription, lote: v.batch })));
                console.groupEnd();
            }
        }

        if (matches.length === 0) return { status: 'none', color: 'border-text-muted/30 text-text-muted/30' };

        const latest = [...matches].sort((a, b) => {
            const dA = a.date ? new Date(a.date).getTime() : 0;
            const dB = b.date ? new Date(b.date).getTime() : 0;
            return dB - dA;
        })[0];

        const app = latest.appearance;
        if (app === 'rejected') return { status: 'rejected', color: 'bg-error border-error text-error' };
        if (app === 'notes' || app === 'warning') return { status: 'warning', color: 'bg-amber-500 border-amber-500 text-amber-500' };
        if (app === 'approved') return { status: 'approved', color: 'bg-success border-success text-success' };

        return { status: 'none', color: 'border-text-muted/30 text-text-muted/30' };
    };

    const columns = [
        {
            header: 'Tipo',
            accessor: (i: Inspection) => (
                <div className={clsx(
                    "w-8 h-8 rounded-lg flex items-center justify-center",
                    i.type === 'surface_treatment' ? "bg-amber-100 text-amber-600" : "bg-primary/10 text-primary"
                )}>
                    {i.type === 'surface_treatment' ? <Hammer size={16} /> : <Paintbrush size={16} />}
                </div>
            ),
            className: "w-12"
        },
        {
            header: 'Obra / Projeto',
            accessor: (i: Inspection) => {
                const project = projects.find(p => p.id === i.projectId);
                return (
                    <div className="flex flex-col">
                        <span className="font-bold text-text-main text-xs uppercase tracking-tight truncate max-w-[150px]" title={project?.name}>
                            {project?.name || '---'}
                        </span>
                        <span className="text-[10px] text-text-muted font-bold uppercase truncate max-w-[150px]">{project?.client || '---'}</span>
                    </div>
                );
            }
        },
        {
            header: 'Data / Inspetor',
            accessor: (i: Inspection) => (
                <div className="flex flex-col">
                    <span className="font-bold text-text-main text-xs uppercase tracking-tight">
                        {i.date ? format(new Date(i.date), 'dd/MM/yyyy') : 'Sem Data'}
                    </span>
                    <span className="text-[10px] text-text-muted font-bold uppercase">{i.inspector || '---'}</span>
                </div>
            )
        },
        {
            header: 'Detalhes',
            accessor: (i: Inspection) => (
                <div className="flex flex-col">
                    <span className="text-text-main font-bold text-xs uppercase">{i.pieceDescription || '--'}</span>
                    {i.type === 'surface_treatment' ? (
                        <div className="flex gap-2 text-[10px] text-text-muted mt-0.5">
                            <span className="bg-surface-hover px-1.5 rounded">{i.treatmentType === 'dry_abrasive_blasting' ? 'Jateamento' : i.treatmentType}</span>
                            <span className="bg-surface-hover px-1.5 rounded font-bold">{i.cleaningDegree}</span>
                        </div>
                    ) : (
                        <span className="text-[10px] text-text-muted mt-0.5">Pintura Convencional</span>
                    )}
                </div>
            )
        },
        {
            header: 'Peso (Kg)',
            accessor: (i: Inspection) => (
                <div className="flex flex-col items-center">
                    <span className="text-text-main font-bold text-xs">{i.weightKg ? i.weightKg.toLocaleString('pt-BR') : '0'}</span>
                    <span className="text-[10px] text-text-muted font-bold tracking-tighter uppercase">KG</span>
                </div>
            )
        },
        {
            header: 'Evidências',
            accessor: (i: Inspection) => i.photos && i.photos.length > 0 ? (
                <div className="flex items-center gap-1 text-text-muted text-xs font-medium">
                    <Camera size={14} />
                    <span>{i.photos.length}</span>
                </div>
            ) : null,
            className: "hidden md:table-cell"
        },
        {
            header: 'Situação',
            accessor: (i: Inspection) => {
                const treat = getStatusIndicator('surface_treatment', i);
                const paint = getStatusIndicator('painting', i);

                const isAnyRejected = treat.status === 'rejected' || paint.status === 'rejected';
                const isBothApproved = treat.status === 'approved' && paint.status === 'approved';
                const isAnyNotes = treat.status === 'warning' || paint.status === 'warning';

                return (
                    <span className={clsx(
                        "px-2 py-0.5 rounded text-[10px] font-black uppercase whitespace-nowrap",
                        isAnyRejected ? "bg-error/10 text-error" :
                            isBothApproved ? "bg-success/10 text-success" :
                                isAnyNotes ? "bg-amber-500/10 text-amber-500" :
                                    "bg-surface-soft text-text-muted"
                    )}>
                        {isAnyRejected ? 'Reprovado' :
                            isBothApproved ? 'Aprovado' :
                                isAnyNotes ? 'Ressalvas' :
                                    'Pendente'}
                    </span>
                );
            }
        },
        {
            header: 'Realizado',
            accessor: (i: Inspection) => {
                const treat = getStatusIndicator('surface_treatment', i);
                const paint = getStatusIndicator('painting', i);

                return (
                    <div className="flex flex-col gap-1.5">
                        <div className="flex items-center gap-2">
                            <div className={clsx("w-2.5 h-2.5 rounded-full border-2", treat.color)}></div>
                            <span className={clsx("text-[10px] font-bold uppercase", treat.status === 'none' ? "text-text-muted/50" : "text-text-secondary")}>Tratamento</span>
                        </div>
                        <div className="flex items-center gap-2">
                            <div className={clsx("w-2.5 h-2.5 rounded-full border-2", paint.color)}></div>
                            <span className={clsx("text-[10px] font-bold uppercase", paint.status === 'none' ? "text-text-muted/50" : "text-text-secondary")}>Pintura</span>
                        </div>
                    </div>
                );
            }
        }
    ];

    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">
                            <ClipboardCheck className="w-8 h-8" />
                        </div>
                        <div>
                            <h1 className="text-3xl md:text-5xl font-black text-text-main tracking-tight mb-0">Inspeções</h1>
                            <p className="text-sm text-text-muted font-medium tracking-widest uppercase text-xs">Controle de qualidade e conformidade</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 inspeções..."
                            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 Inspeção
                    </Button>
                </div>
            </div>

            <div className="bg-surface rounded-[32px] border border-border/40 shadow-soft p-2">
                <MobileList
                    data={filteredInspections}
                    columns={columns}
                    keyExtractor={(item) => item.id}
                    titleAccessor={(item) => item.date ? format(new Date(item.date), 'dd/MM/yyyy') : 'Sem data'}
                    subtitleAccessor={(item) => `${item.inspector || ''} - ${item.pieceDescription || ''}`}
                    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 inspeção"
                                title="Editar inspeção"
                            >
                                <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 inspeção"
                                title="Excluir inspeção"
                            >
                                <Trash2 size={18} />
                            </button>
                        </div>
                    )}
                />

                {filteredInspections.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">
                            <ClipboardCheck className="w-10 h-10" />
                        </div>
                        <h3 className="text-xl font-bold text-text-main">Nenhuma inspeção encontrada</h3>
                        <p className="mt-2 text-text-muted font-medium">Os registros de qualidade aparecerão aqui após serem realizados.</p>
                    </div>
                )}
            </div>

            <CreateInspectionModal
                isOpen={isModalOpen}
                onClose={() => { setIsModalOpen(false); setEditItem(undefined); }}
                onSuccess={fetchInspections}
                initialData={editItem}
                existingInspections={inspections}
            />
        </div>
    );
};

