import { useState } from 'react';
import { Plus, Edit, Trash2, MoreVertical } from 'lucide-react';
import { PageHeader } from '@/components/common/PageHeader';
import { ServerDataTable } from '@/components/common/ServerDataTable';
import { Button } from '@/components/ui/button';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useMinistries } from '@/hooks/useMinistries';
import { MinistryDTO } from '@/types/org';
import { useToast } from '@/hooks/use-toast';
import { MinistryFormModal } from './components/MinistryFormModal';
import { ConfirmDialog } from '@/components/common/ConfirmDialog';

export function MinistryList() {
    const [searchTerm, setSearchTerm] = useState('');
    const [selectedMinistry, setSelectedMinistry] = useState<MinistryDTO | null>(null);
    const [isFormOpen, setIsFormOpen] = useState(false);
    const [isDeleteOpen, setIsDeleteOpen] = useState(false);
    const { toast } = useToast();

    const {
        ministries,
        loading,
        error,
        page,
        totalPages,
        totalElements,
        setPage,
        createMinistry,
        updateMinistry,
        deleteMinistry,
        refetch,
    } = useMinistries({
        page: 0,
        size: 20,
        sortBy: 'code',
        sortDirection: 'ASC',
    });

    // Client-side filtering for now if backend search not implemented
    const filteredMinistries = ministries.filter((ministry) =>
        ministry.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        ministry.code.toLowerCase().includes(searchTerm.toLowerCase()) ||
        ministry.acronym.toLowerCase().includes(searchTerm.toLowerCase())
    );

    const handleCreate = () => {
        setSelectedMinistry(null);
        setIsFormOpen(true);
    };

    const handleEdit = (ministry: MinistryDTO) => {
        setSelectedMinistry(ministry);
        setIsFormOpen(true);
    };

    const handleDelete = (ministry: MinistryDTO) => {
        setSelectedMinistry(ministry);
        setIsDeleteOpen(true);
    };

    const handleDeleteConfirm = async () => {
        if (!selectedMinistry) return;

        try {
            await deleteMinistry(selectedMinistry.id);
            toast({
                title: 'Sucesso',
                description: 'Ministério excluído com sucesso',
            });
            setIsDeleteOpen(false);
            setSelectedMinistry(null);
        } catch (err: any) {
            toast({
                title: 'Erro',
                description: err.message || 'Erro ao excluir ministério',
                variant: 'destructive',
            });
        }
    };

    const handleFormSubmit = async (data: any) => {
        try {
            if (selectedMinistry) {
                await updateMinistry(selectedMinistry.id, data);
                toast({
                    title: 'Sucesso',
                    description: 'Ministério atualizado com sucesso',
                });
            } else {
                await createMinistry(data);
                toast({
                    title: 'Sucesso',
                    description: 'Ministério criado com sucesso',
                });
            }
            setIsFormOpen(false);
            setSelectedMinistry(null);
        } catch (err: any) {
            toast({
                title: 'Erro',
                description: err.message || 'Erro ao salvar ministério',
                variant: 'destructive',
            });
        }
    };

    const columns = [
        {
            key: 'logo',
            header: 'Logo',
            cell: (ministry: MinistryDTO) => (
                ministry.logo ? (
                    <img
                        src={ministry.logo}
                        alt={ministry.acronym}
                        className="h-8 w-8 object-contain rounded border bg-white"
                    />
                ) : (
                    <div className="h-8 w-8 rounded border bg-gray-100 flex items-center justify-center text-xs text-gray-400">
                        N/A
                    </div>
                )
            ),
        },
        {
            key: 'code',
            header: 'Código',
            cell: (ministry: MinistryDTO) => ministry.code,
        },
        {
            key: 'acronym',
            header: 'Sigla',
            cell: (ministry: MinistryDTO) => <span className="font-medium">{ministry.acronym}</span>,
        },
        {
            key: 'name',
            header: 'Nome',
            cell: (ministry: MinistryDTO) => ministry.name,
        },
        {
            key: 'actions',
            header: 'Ações',
            cell: (ministry: MinistryDTO) => (
                <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                        <Button variant="ghost" size="sm">
                            <MoreVertical className="h-4 w-4" />
                        </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                        <DropdownMenuItem onClick={() => handleEdit(ministry)}>
                            <Edit className="mr-2 h-4 w-4" />
                            Editar
                        </DropdownMenuItem>
                        <DropdownMenuItem
                            onClick={() => handleDelete(ministry)}
                            className="text-destructive"
                        >
                            <Trash2 className="mr-2 h-4 w-4" />
                            Excluir
                        </DropdownMenuItem>
                    </DropdownMenuContent>
                </DropdownMenu>
            ),
        },
    ];

    return (
        <div className="space-y-6">
            <PageHeader
                title="Ministérios"
                description="Gestão de Ministérios e Órgãos Superiores"
            />

            {/* Actions Bar */}
            <div className="flex items-center justify-end gap-4">
                <Button onClick={handleCreate}>
                    <Plus className="mr-2 h-4 w-4" />
                    Novo Ministério
                </Button>
            </div>

            {/* Table */}
            <ServerDataTable
                data={filteredMinistries}
                columns={columns}
                loading={loading}
                error={error}
                page={page}
                totalPages={totalPages}
                totalElements={totalElements}
                pageSize={20}
                onPageChange={setPage}
                onSearch={setSearchTerm}
                searchPlaceholder="Pesquisar por nome, código ou sigla..."
                emptyMessage="Nenhum ministério encontrado"
            />

            {/* Modals */}
            <MinistryFormModal
                open={isFormOpen}
                onOpenChange={setIsFormOpen}
                ministry={selectedMinistry}
                onSubmit={handleFormSubmit}
            />

            <ConfirmDialog
                open={isDeleteOpen}
                onOpenChange={setIsDeleteOpen}
                title="Excluir Ministério"
                description={`Tem certeza que deseja excluir o ministério "${selectedMinistry?.name}"?`}
                onConfirm={handleDeleteConfirm}
            />
        </div>
    );
}
