import React, { useState, useEffect } from 'react';
import { Building, Plus, Trash2, Edit2, Search, X, Landmark, ShieldCheck } from 'lucide-react';
import { PageHeader } from '@/components/common/PageHeader';
import { Button } from '@/components/ui/button';
import { commonService } from '../../../services/commonService';
import { BankDTO } from '../../../types/common';
import { toast } from 'sonner';

export const BanksPage: React.FC = () => {
    const [banks, setBanks] = useState<BankDTO[]>([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingBank, setEditingBank] = useState<BankDTO | null>(null);

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

    const loadBanks = async () => {
        try {
            setLoading(true);
            const response = await commonService.getBanks({ page: 0, size: 100 });
            setBanks(response.content);
        } catch (error) {
            toast.error('Erro ao carregar lista de bancos');
        } finally {
            setLoading(false);
        }
    };

    const handleEdit = (bank: BankDTO) => {
        setEditingBank(bank);
        setIsModalOpen(true);
    };

    const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        const formData = new FormData(e.currentTarget);
        const data: BankDTO = {
            code: formData.get('code') as string,
            name: formData.get('name') as string,
            swiftCode: formData.get('swiftCode') as string || undefined
        };

        try {
            if (editingBank?.id) {
                await commonService.updateBank(editingBank.id, data);
                toast.success('Banco atualizado com sucesso');
            } else {
                await commonService.createBank(data);
                toast.success('Banco cadastrado com sucesso');
            }
            setIsModalOpen(false);
            setEditingBank(null);
            loadBanks();
        } catch (error) {
            toast.error('Erro ao salvar banco');
        }
    };

    return (
        <div className="p-6 space-y-6">
            <PageHeader
                title="Cadastro de Bancos"
                description="Gestão de entidades bancárias autorizadas para pagamento"
                actions={
                    <Button onClick={() => { setEditingBank(null); setIsModalOpen(true); }} className="flex items-center gap-2">
                        <Plus className="w-4 h-4" /> Novo Banco
                    </Button>
                }
            />

            <div className="bg-white rounded-lg shadow overflow-hidden border">
                <table className="min-w-full divide-y divide-gray-200">
                    <thead className="bg-gray-50 text-gray-500 uppercase text-xs font-semibold tracking-wider">
                        <tr>
                            <th className="px-6 py-3 text-left">Código</th>
                            <th className="px-6 py-3 text-left">Nome do Banco</th>
                            <th className="px-6 py-3 text-left">SWIFT / BIC</th>
                            <th className="px-6 py-3 text-right">Ações</th>
                        </tr>
                    </thead>
                    <tbody className="bg-white divide-y divide-gray-200 text-sm">
                        {loading ? (
                            <tr><td colSpan={4} className="px-6 py-4 text-center">Carregando dados...</td></tr>
                        ) : banks.length === 0 ? (
                            <tr><td colSpan={4} className="px-6 py-4 text-center text-gray-500">Nenhum banco cadastrado</td></tr>
                        ) : (
                            banks.map((bank) => (
                                <tr key={bank.id} className="hover:bg-gray-50">
                                    <td className="px-6 py-4 font-bold text-gray-700">{bank.code}</td>
                                    <td className="px-6 py-4">
                                        <div className="flex items-center gap-2 text-gray-900 font-medium">
                                            <Landmark className="w-4 h-4 text-gray-400" />
                                            {bank.name}
                                        </div>
                                    </td>
                                    <td className="px-6 py-4 font-mono text-gray-500">{bank.swiftCode || '---'}</td>
                                    <td className="px-6 py-4 text-right space-x-2">
                                        <Button variant="ghost" size="sm" onClick={() => handleEdit(bank)} className="text-blue-600 hover:bg-blue-50">
                                            <Edit2 className="w-4 h-4" />
                                        </Button>
                                    </td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>

            {isModalOpen && (
                <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
                    <div className="bg-white rounded-xl shadow-2xl max-w-md w-full overflow-hidden">
                        <div className="px-6 py-4 border-b flex justify-between items-center bg-gray-50">
                            <h3 className="text-lg font-bold text-gray-900">
                                {editingBank ? 'Editar Banco' : 'Novo Banco'}
                            </h3>
                            <button onClick={() => setIsModalOpen(false)} className="text-gray-400 hover:text-gray-600">
                                <X className="w-5 h-5" />
                            </button>
                        </div>
                        <form onSubmit={handleSubmit} className="p-6 space-y-4">
                            <div className="grid grid-cols-3 gap-4">
                                <div className="space-y-1 col-span-1">
                                    <label className="text-xs font-bold text-gray-500 uppercase">Código</label>
                                    <input
                                        name="code"
                                        required
                                        defaultValue={editingBank?.code}
                                        placeholder="001"
                                        className="w-full border rounded-lg p-2 text-sm focus:ring-2 focus:ring-primary focus:outline-none"
                                    />
                                </div>
                                <div className="space-y-1 col-span-2">
                                    <label className="text-xs font-bold text-gray-500 uppercase">SWIFT/BIC (Opcional)</label>
                                    <input
                                        name="swiftCode"
                                        defaultValue={editingBank?.swiftCode}
                                        placeholder="EX: BAOGWGBXXX"
                                        className="w-full border rounded-lg p-2 text-sm font-mono focus:ring-2 focus:ring-primary focus:outline-none uppercase"
                                    />
                                </div>
                            </div>

                            <div className="space-y-1">
                                <label className="text-xs font-bold text-gray-500 uppercase">Nome Completo do Banco</label>
                                <input
                                    name="name"
                                    required
                                    defaultValue={editingBank?.name}
                                    placeholder="Ex: Banco da África Ocidental"
                                    className="w-full border rounded-lg p-2 text-sm focus:ring-2 focus:ring-primary focus:outline-none"
                                />
                            </div>

                            <div className="pt-4 flex gap-3">
                                <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)} className="flex-1">Cancelar</Button>
                                <Button type="submit" className="flex-1">Salvar</Button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            <div className="p-4 bg-amber-50 border border-amber-200 rounded-lg flex gap-3 text-amber-800 text-sm">
                <ShieldCheck className="w-5 h-5 flex-shrink-0" />
                <p>O cadastro de bancos é uma tabela base. Alterações aqui impactam diretamente as remessas bancárias geradas pela Tesouraria.</p>
            </div>
        </div>
    );
};
