import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { PageHeader } from '@/components/common/PageHeader';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { attendanceService } from '@/services/attendanceService';
import { AttendanceRecordDTO } from '@/types/attendance';
import { toast } from 'sonner';
import { ArrowLeft, Upload, CheckCircle2 } from 'lucide-react';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';

export function AttendanceSheetPage() {
    const { id } = useParams<{ id: string }>();
    const navigate = useNavigate();
    const [records, setRecords] = useState<AttendanceRecordDTO[]>([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        if (id) loadData();
    }, [id]);

    const loadData = async () => {
        try {
            setLoading(true);
            if (!id) return;
            const recs = await attendanceService.getRecords(id);
            setRecords(recs);
        } catch (error) {
            toast.error('Erro ao carregar dados');
        } finally {
            setLoading(false);
        }
    };

    const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files && e.target.files[0] && id) {
            try {
                await attendanceService.uploadExcel(id, e.target.files[0]);
                toast.success('Upload realizado com sucesso');
                loadData();
            } catch (error) {
                toast.error('Erro no upload');
            }
        }
    };

    const handleApprove = async () => {
        if (!id) return;
        try {
            await attendanceService.approveSheet(id);
            toast.success('Folha aprovada com sucesso');
            navigate('/rh/attendance');
        } catch (error) {
            toast.error('Erro ao aprovar');
        }
    };

    if (loading) return <div className="p-8">Carregando...</div>;

    return (
        <div className="p-6 space-y-6">
            <div className="flex justify-between items-center">
                <PageHeader
                    title="Editor de Frequência"
                    description="Visualize e edite as ocorrências mensais."
                />
                <div className="flex gap-2">
                    <Button variant="outline" onClick={() => navigate('/rh/attendance')}>
                        <ArrowLeft className="mr-2 h-4 w-4" /> Voltar
                    </Button>

                    <div className="relative">
                        <input
                            type="file"
                            onChange={handleUpload}
                            className="absolute inset-0 opacity-0 cursor-pointer"
                            accept=".xlsx,.xls"
                        />
                        <Button variant="secondary">
                            <Upload className="mr-2 h-4 w-4" /> Importar Excel
                        </Button>
                    </div>

                    <Button onClick={handleApprove} className="bg-green-600 hover:bg-green-700">
                        <CheckCircle2 className="mr-2 h-4 w-4" /> Aprovar Folha
                    </Button>
                </div>
            </div>

            <Card>
                <CardContent className="p-0">
                    <div className="p-8 text-center text-gray-500">
                        <p>Nesta versão MVP, por favor utilize a funcionalidade <strong>Importar Excel</strong> para popular os dados.</p>
                        <p className="text-sm mt-2">O modo "Matriz de Edição Online" será liberado na próxima atualização.</p>

                        <div className="mt-8 border rounded-lg p-4 bg-gray-50 text-left max-w-2xl mx-auto">
                            <h3 className="font-bold mb-2">Instruções para Excel:</h3>
                            <ul className="list-disc pl-5 space-y-1 text-sm">
                                <li>Coluna A: Matrícula do Funcionário</li>
                                <li>Colunas B até AE: Dias do mês (1 a 31)</li>
                                <li>Códigos: <strong>F</strong> (Falta), <strong>V</strong> (Férias), <strong>M</strong> (Médica)</li>
                                <li>Células vazias são consideradas "Presença".</li>
                            </ul>
                        </div>
                    </div>

                    {records.length > 0 && (
                        <div className="border-t">
                            <div className="p-4 bg-gray-100 font-bold text-xs uppercase text-gray-500">
                                Registros de Exceção Importados ({records.length})
                            </div>
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Funcionário</TableHead>
                                        <TableHead>Data</TableHead>
                                        <TableHead>Tipo</TableHead>
                                        <TableHead>Observação</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {records.map(rec => (
                                        <TableRow key={rec.id}>
                                            <TableCell>{rec.agentName}</TableCell>
                                            <TableCell>{rec.date}</TableCell>
                                            <TableCell>
                                                <span className="px-2 py-1 rounded-full text-xs font-bold bg-red-100 text-red-800">
                                                    {rec.type}
                                                </span>
                                            </TableCell>
                                            <TableCell>{rec.observation}</TableCell>
                                        </TableRow>
                                    ))}
                                </TableBody>
                            </Table>
                        </div>
                    )}
                </CardContent>
            </Card>
        </div>
    );
}
