import React, { useEffect, useState } from 'react';
import api from '../services/api';
import { Button } from '../components/Button';
import { Plus, Pencil, Trash2, Layers, Search, Copy } from 'lucide-react';
import { MobileList } from '../components/MobileList';
import { CreatePaintingSchemeModal } from '../components/modals/CreatePaintingSchemeModal';
import { CloneSchemeModal } from '../components/modals/CloneSchemeModal';
import type { PaintingScheme } from '../types';

import { useAuth } from '../context/useAuth';

export const SchemesList: React.FC = () => {
    const { isAdmin } = useAuth();
    const [schemes, setSchemes] = useState<PaintingScheme[]>([]);
    const [loading, setLoading] = useState(true);
    const [editItem, setEditItem] = useState<PaintingScheme | undefined>(undefined);
    const [cloneItem, setCloneItem] = useState<PaintingScheme | undefined>(undefined);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isCloneModalOpen, setIsCloneModalOpen] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');

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

    const fetchSchemes = async () => {
        try {
            const response = await api.get('/painting-schemes');
            console.log("Fetched schemes (JSON):", JSON.stringify(response.data, null, 2));
            setSchemes(response.data);
        } catch (error) {
            console.error('Error fetching schemes:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleDelete = async (id: string) => {
        if (!window.confirm('Tem certeza que deseja excluir este esquema?')) return;
        try {
            await api.delete(`/painting-schemes/${id}`);
            fetchSchemes();
        } catch (error) {
            console.error('Error deleting scheme', error);
        }
    };

    const filteredSchemes = schemes.filter(s =>
        s.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        (s.type && s.type.toLowerCase().includes(searchTerm.toLowerCase())) ||
        (s.manufacturer && s.manufacturer.toLowerCase().includes(searchTerm.toLowerCase()))
    );

    const columns = [
        {
            header: 'Esquema / Produto',
            accessor: (s: PaintingScheme) => (
                <div className="flex flex-col">
                    <span className="font-bold text-text-main text-xs uppercase tracking-tight">{s.name}</span>
                    <span className="text-[10px] text-text-muted font-bold uppercase">{s.manufacturer || '---'}</span>
                </div>
            )
        },
        {
            header: 'Tipo',
            accessor: (s: PaintingScheme) => (
                <span className="text-text-secondary font-medium text-xs uppercase">{s.type || '--'}</span>
            )
        },
        {
            header: 'Demão',
            accessor: (s: PaintingScheme) => (
                <span className="text-text-secondary font-medium text-xs uppercase">{s.coat || '--'}</span>
            )
        },
        {
            header: 'Cor',
            accessor: (s: PaintingScheme) => (
                <span className="text-text-secondary font-medium text-xs uppercase">{s.color || '--'}</span>
            )
        },
        {
            header: 'EPS (Min)',
            accessor: (s: PaintingScheme) => (
                <span className="text-text-secondary font-medium text-xs">{s.epsMin ? `${s.epsMin} µm` : '--'}</span>
            )
        },
        {
            header: 'SV%',
            accessor: (s: PaintingScheme) => (
                <span className="text-text-secondary font-medium text-xs">{s.solidsVolume ? `${s.solidsVolume}%` : '--'}</span>
            )
        },
        {
            header: 'Rendimento',
            accessor: (s: PaintingScheme) => (
                <span className="text-primary font-black text-xs">{s.yieldTheoretical ? `${s.yieldTheoretical} m²/L` : '--'}</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">
                            <Layers className="w-8 h-8" />
                        </div>
                        <div>
                            <h1 className="text-3xl md:text-5xl font-black text-text-main tracking-tight mb-0">Esquemas de Pintura</h1>
                            <p className="text-sm text-text-muted font-medium tracking-widest uppercase text-xs">Especificações e rendimentos teóricos</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 esquemas..."
                            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>
                    {isAdmin() && (
                        <Button onClick={() => { setEditItem(undefined); setIsModalOpen(true); }} size="lg" className="shadow-primary/30 h-14">
                            <Plus className="w-5 h-5 mr-2" />
                            Novo Esquema
                        </Button>
                    )}
                </div>
            </div>

            <div className="bg-surface rounded-[32px] border border-border/40 shadow-soft p-2">
                <MobileList
                    data={filteredSchemes}
                    columns={columns}
                    keyExtractor={(item) => item.id}
                    titleAccessor="name"
                    subtitleAccessor={(item) => `${item.manufacturer || ''} ${item.type || ''}`}
                    actionRender={(item) => isAdmin() ? (
                        <div className="flex gap-1 justify-end">
                            <button
                                onClick={() => { setCloneItem(item); setIsCloneModalOpen(true); }}
                                className="p-2 text-text-muted hover:text-green-500 hover:bg-green-500/10 rounded-xl transition-all"
                                aria-label="Clonar esquema"
                                title="Clonar para outra obra"
                            >
                                <Copy size={18} />
                            </button>
                            <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 esquema"
                                title="Editar esquema"
                            >
                                <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 esquema"
                                title="Excluir esquema"
                            >
                                <Trash2 size={18} />
                            </button>
                        </div>
                    ) : null}
                />

                {filteredSchemes.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">
                            <Layers className="w-10 h-10" />
                        </div>
                        <h3 className="text-xl font-bold text-text-main">Nenhum esquema encontrado</h3>
                        <p className="mt-2 text-text-muted font-medium">Cadastre os sistemas de pintura para utilizá-los nas obras.</p>
                    </div>
                )}
            </div>

            <CreatePaintingSchemeModal
                isOpen={isModalOpen}
                onClose={() => { setIsModalOpen(false); setEditItem(undefined); }}
                onSuccess={fetchSchemes}
                initialData={editItem}
            />
            <CloneSchemeModal
                isOpen={isCloneModalOpen}
                onClose={() => { setIsCloneModalOpen(false); setCloneItem(undefined); }}
                onSuccess={fetchSchemes}
                schemeToClone={cloneItem}
            />
        </div>
    );
};

