import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { PageHeader } from '@/components/common/PageHeader';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { useOrgUnits } from '@/hooks/useOrgUnits';
import { attendanceService } from '@/services/attendanceService';
import { MonthlyAttendanceSheetDTO } from '@/types/attendance';
import { toast } from 'sonner';
import { FileSpreadsheet, CheckCircle2, AlertCircle, Lock } from 'lucide-react';

export function AttendanceDashboard() {
    const navigate = useNavigate();
    const { orgUnits } = useOrgUnits({ size: 100 });
    const [selectedOrgId, setSelectedOrgId] = useState<string>('');
    const [month, setMonth] = useState<number>(new Date().getMonth() + 1);
    const [year, setYear] = useState<number>(new Date().getFullYear());
    const [sheet, setSheet] = useState<MonthlyAttendanceSheetDTO | null>(null);
    const [loading, setLoading] = useState(false);

    const handleSearch = async () => {
        if (!selectedOrgId) {
            toast.error('Selecione uma Unidade Orgânica');
            return;
        }

        try {
            setLoading(true);
            const data = await attendanceService.getSheet(selectedOrgId, month, year);
            setSheet(data);
        } catch (error) {
            toast.error('Erro ao buscar folha de ponto');
        } finally {
            setLoading(false);
        }
    };

    const getStatusColor = (status: string) => {
        switch (status) {
            case 'DRAFT': return 'bg-yellow-100 text-yellow-800 border-yellow-200';
            case 'SUBMITTED': return 'bg-blue-100 text-blue-800 border-blue-200';
            case 'APPROVED': return 'bg-green-100 text-green-800 border-green-200';
            case 'CLOSED': return 'bg-gray-100 text-gray-800 border-gray-200';
            default: return 'bg-gray-100';
        }
    };

    return (
        <div className="p-6 space-y-6">
            <PageHeader
                title="Gestão de Assiduidade"
                description="Controle mensal de frequência descentralizado por unidade orgânica."
            />

            <Card>
                <CardHeader>
                    <CardTitle>Seleção da Folha</CardTitle>
                    <CardDescription>Selecione a unidade e o período para gerenciar a frequência.</CardDescription>
                </CardHeader>
                <CardContent className="flex gap-4 items-end">
                    <div className="flex-1 space-y-2">
                        <label className="text-sm font-medium">Unidade Orgânica</label>
                        <Select value={selectedOrgId} onValueChange={setSelectedOrgId}>
                            <SelectTrigger>
                                <SelectValue placeholder="Selecione..." />
                            </SelectTrigger>
                            <SelectContent>
                                {orgUnits.map(unit => (
                                    <SelectItem key={unit.id} value={unit.id}>{unit.code} - {unit.name}</SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </div>

                    <div className="w-32 space-y-2">
                        <label className="text-sm font-medium">Mês</label>
                        <Select value={month.toString()} onValueChange={(v) => setMonth(parseInt(v))}>
                            <SelectTrigger>
                                <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                                {Array.from({ length: 12 }, (_, i) => i + 1).map(m => (
                                    <SelectItem key={m} value={m.toString()}>{m}</SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </div>

                    <div className="w-32 space-y-2">
                        <label className="text-sm font-medium">Ano</label>
                        <Input type="number" value={year} onChange={(e) => setYear(parseInt(e.target.value))} />
                    </div>

                    <Button onClick={handleSearch} disabled={loading}>
                        {loading ? 'Buscando...' : 'Buscar Folha'}
                    </Button>
                </CardContent>
            </Card>

            {sheet && (
                <Card className="border-l-4 border-l-primary">
                    <CardHeader>
                        <div className="flex justify-between items-start">
                            <div>
                                <CardTitle className="text-lg">Folha de Ponto: {month}/{year}</CardTitle>
                                <CardDescription>
                                    {orgUnits.find(u => u.id === selectedOrgId)?.name}
                                </CardDescription>
                            </div>
                            <span className={`px-3 py-1 rounded-full text-xs font-bold border ${getStatusColor(sheet.status)}`}>
                                {sheet.status}
                            </span>
                        </div>
                    </CardHeader>
                    <CardContent>
                        <div className="flex gap-4">
                            <Button onClick={() => navigate(`/rh/attendance/${sheet.id}`)} variant="default">
                                <FileSpreadsheet className="mr-2 h-4 w-4" />
                                Abrir / Editar Frequência
                            </Button>

                            {sheet.status === 'APPROVED' && (
                                <div className="flex items-center text-green-700 gap-2 text-sm font-medium px-4 bg-green-50 rounded-md border border-green-100">
                                    <CheckCircle2 className="h-4 w-4" />
                                    Aprovado por: {sheet.approvedBy || 'Direção'}
                                </div>
                            )}

                            {sheet.status === 'CLOSED' && (
                                <div className="flex items-center text-gray-700 gap-2 text-sm font-medium px-4 bg-gray-50 rounded-md border border-gray-100">
                                    <Lock className="h-4 w-4" />
                                    Processado na Folha de Pagamento
                                </div>
                            )}
                        </div>
                    </CardContent>
                </Card>
            )}
        </div>
    );
}
