import React, { useState, useEffect } from 'react';
import { Calendar, Plus, Play, Lock, CheckCircle, AlertCircle } from 'lucide-react';
import { PageHeader } from '@/components/common/PageHeader';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { rhService } from '../../../services/rhService';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { pt } from 'date-fns/locale';

export const PayrollPeriodsPage: React.FC = () => {
    const [periods, setPeriods] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);

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

    const loadPeriods = async () => {
        try {
            setLoading(true);
            const data = await rhService.getPayrollPeriods();
            setPeriods(data);
        } catch (error) {
            toast.error('Erro ao carregar períodos');
        } finally {
            setLoading(false);
        }
    };

    const handleCreatePeriod = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        const formData = new FormData(e.currentTarget);
        const data = {
            fiscalYear: parseInt(formData.get('fiscalYear') as string),
            month: parseInt(formData.get('month') as string),
            startDate: formData.get('startDate'),
            endDate: formData.get('endDate')
        };

        try {
            await rhService.createPayrollPeriod(data);
            toast.success('Período criado com sucesso');
            setIsCreateModalOpen(false);
            loadPeriods();
        } catch (error) {
            toast.error('Erro ao criar período');
        }
    };

    const handleStatusUpdate = async (id: string, status: string) => {
        try {
            await rhService.updatePayrollPeriodStatus(id, status);
            toast.success(`Período ${status === 'OPEN' ? 'aberto' : 'fechado'} com sucesso`);
            loadPeriods();
        } catch (error) {
            toast.error('Erro ao atualizar status');
        }
    };

    const getStatusBadge = (status: string) => {
        switch (status) {
            case 'OPEN':
                return <span className="px-2 py-1 text-xs font-semibold bg-green-100 text-green-700 rounded-full flex items-center gap-1"><Play className="w-3 h-3" /> Aberto</span>;
            case 'CLOSED':
                return <span className="px-2 py-1 text-xs font-semibold bg-gray-100 text-gray-700 rounded-full flex items-center gap-1"><Lock className="w-3 h-3" /> Fechado</span>;
            default:
                return <span className="px-2 py-1 text-xs font-semibold bg-blue-100 text-blue-700 rounded-full">Rascunho</span>;
        }
    };

    return (
        <div className="p-6 space-y-6">
            <PageHeader
                title="Períodos de Folha"
                description="Gestão de meses de processamento e calendários fiscais"
                icon={Calendar}
                actions={
                    <Button onClick={() => setIsCreateModalOpen(true)} className="flex items-center gap-2">
                        <Plus className="w-4 h-4" /> Novo Período
                    </Button>
                }
            />

            {loading ? (
                <div className="flex justify-center p-12">Processando...</div>
            ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {periods.map((period) => (
                        <Card key={period.id} className="hover:shadow-md transition-shadow">
                            <CardHeader className="pb-2">
                                <div className="flex justify-between items-start">
                                    <CardTitle className="text-lg font-bold text-primary">
                                        {format(new Date(period.fiscalYear, period.month - 1), 'MMMM yyyy', { locale: pt })}
                                    </CardTitle>
                                    {getStatusBadge(period.status)}
                                </div>
                            </CardHeader>
                            <CardContent>
                                <div className="space-y-3 text-sm">
                                    <div className="flex justify-between text-muted-foreground">
                                        <span>Início:</span>
                                        <span className="font-medium text-foreground">{format(new Date(period.startDate), 'dd/MM/yyyy')}</span>
                                    </div>
                                    <div className="flex justify-between text-muted-foreground">
                                        <span>Fim:</span>
                                        <span className="font-medium text-foreground">{format(new Date(period.endDate), 'dd/MM/yyyy')}</span>
                                    </div>
                                    <div className="pt-4 flex gap-2">
                                        {period.status === 'OPEN' ? (
                                            <Button
                                                onClick={() => handleStatusUpdate(period.id, 'CLOSED')}
                                                variant="outline" size="sm" className="w-full text-orange-600 border-orange-200 hover:bg-orange-50"
                                            >
                                                Fechar Período
                                            </Button>
                                        ) : period.status === 'DRAFT' || period.status === 'PENDING' ? (
                                            <Button
                                                onClick={() => handleStatusUpdate(period.id, 'OPEN')}
                                                variant="default" size="sm" className="w-full"
                                            >
                                                Abrir Período
                                            </Button>
                                        ) : (
                                            <Button disabled variant="secondary" size="sm" className="w-full">
                                                Concluído
                                            </Button>
                                        )}
                                    </div>
                                </div>
                            </CardContent>
                        </Card>
                    ))}
                </div>
            )}

            {isCreateModalOpen && (
                <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
                    <Card className="w-full max-w-md">
                        <CardHeader>
                            <CardTitle>Abrir Novo Período</CardTitle>
                        </CardHeader>
                        <CardContent>
                            <form onSubmit={handleCreatePeriod} className="space-y-4">
                                <div>
                                    <label className="text-sm font-medium">Ano Fiscal (ID)</label>
                                    <input name="fiscalYearId" required className="w-full p-2 border rounded mt-1" placeholder="UUID do Ano Fiscal" />
                                </div>
                                <div className="grid grid-cols-2 gap-4">
                                    <div>
                                        <label className="text-sm font-medium">Mês (1-12)</label>
                                        <input name="month" type="number" min="1" max="12" required className="w-full p-2 border rounded mt-1" />
                                    </div>
                                </div>
                                <div>
                                    <label className="text-sm font-medium">Data de Início</label>
                                    <input name="startDate" type="date" required className="w-full p-2 border rounded mt-1" />
                                </div>
                                <div>
                                    <label className="text-sm font-medium">Data de Fim</label>
                                    <input name="endDate" type="date" required className="w-full p-2 border rounded mt-1" />
                                </div>
                                <div className="flex justify-end gap-2 pt-4">
                                    <Button type="button" variant="ghost" onClick={() => setIsCreateModalOpen(false)}>Cancelar</Button>
                                    <Button type="submit">Criar Período</Button>
                                </div>
                            </form>
                        </CardContent>
                    </Card>
                </div>
            )}
        </div>
    );
};
