"use client";

import type React from "react";
import Link from "next/link";
import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Calendar as CalendarIcon, RefreshCw } from "lucide-react";
import { Calendar } from "@/components/ui/calendar";
import { format } from "date-fns";
import { useRouter } from "next/navigation";
import { toast } from "@/hooks/use-toast";

// [TIPAGEM] Interfaces importadas ou definidas localmente conforme a documentação
import { excecoesApi } from "@/services/excecoesApi";
import { agendamentosApi, Appointment } from "@/services/agendamentosApi";
import { usuariosApi, User } from "@/services/usuariosApi";

// Tipos definidos localmente baseados na documentação da API, já que não são exportados pelos serviços
interface DoctorExceptionCreate {
    doctor_id: string;
    created_by: string;
    date: string;
    start_time?: string;
    end_time?: string;
    kind: 'bloqueio' | 'liberacao';
    reason?: string | FormDataEntryValue | null;
}

interface Profile {
    id: string;
    full_name: string;
    [key: string]: any;
}

interface UserInfoResponse {
    user: User;
    profile: Profile;
    roles: string[];
}

export default function ExceptionPage() {
    const router = useRouter();

    // [ESTADO] Estados robustos para dados, carregamento e erro
    const [appointments, setAppointments] = useState<Appointment[]>([]);
    const [userInfo, setUserInfo] = useState<UserInfoResponse | null>(null);
    const [isLoading, setIsLoading] = useState(true);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const [bookedDays, setBookedDays] = useState<Date[]>([]);
    const [selectedCalendarDate, setSelectedCalendarDate] = useState<Date | undefined>(new Date());
    const [tipo, setTipo] = useState<'bloqueio' | 'liberacao' | "">("");

    // [API] Função centralizada e corrigida para buscar dados
    const fetchData = async () => {
        setIsLoading(true);
        setError(null);
        try {
            // A função getFullData precisa de um ID, então buscamos o usuário atual primeiro.
            const currentUser = await usuariosApi.getCurrentUser();
            if (!currentUser || !currentUser.id) {
                throw new Error("Usuário não autenticado.");
            }

            const [userData, appointmentsData] = await Promise.all([
                usuariosApi.getFullData(currentUser.id), // Corrigido: Passando o ID do usuário
                agendamentosApi.list()
            ]);

            setUserInfo(userData as UserInfoResponse);
            setAppointments(appointmentsData);

            const booked = appointmentsData.map(app => new Date(app.scheduled_at));
            setBookedDays(booked);
        } catch (err: any) {
            const errorMessage = err.message || "Erro ao carregar os dados da agenda. Tente novamente.";
            setError(errorMessage);
            toast({
                title: "Erro de Carregamento",
                description: errorMessage,
                variant: "destructive",
            });
        } finally {
            setIsLoading(false);
        }
    };

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

    const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        if (isSubmitting || !userInfo?.profile?.id || !userInfo?.user?.id) return;

        setIsSubmitting(true);
        const form = e.currentTarget;
        const formData = new FormData(form);

        const apiPayload: DoctorExceptionCreate = {
            doctor_id: userInfo.profile.id,
            created_by: userInfo.user.id,
            date: selectedCalendarDate ? format(selectedCalendarDate, "yyyy-MM-dd") : "",
            start_time: (formData.get("horarioEntrada") as string) + ":00",
            end_time: (formData.get("horarioSaida") as string) + ":00",
            kind: tipo as 'bloqueio' | 'liberacao',
            reason: formData.get("reason"),
        };

        try {
            await excecoesApi.create(apiPayload);
            toast({
                title: "Sucesso",
                description: "Exceção cadastrada com sucesso.",
            });
            router.push("/doctor/dashboard");
        } catch (err: any) {
            toast({
                title: "Erro ao Salvar",
                description: err?.message || "Não foi possível cadastrar a exceção.",
                variant: "destructive",
            });
        } finally {
            setIsSubmitting(false);
        }
    };

    const displayDate = selectedCalendarDate ? new Date(selectedCalendarDate).toLocaleDateString("pt-BR", { weekday: "long", day: "2-digit", month: "long" }) : "Selecione uma data";

    // [UI] Feedback Visual para Carregamento e Erro
    if (isLoading) {
        return <div className="flex justify-center items-center h-64 p-4">Carregando dados da agenda...</div>;
    }

    if (error) {
        return <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-md text-center">{error}</div>;
    }

    return (
        <div className="space-y-6">
            <div>
                <h1 className="text-3xl font-bold text-gray-900">Adicionar exceções</h1>
                <p className="text-gray-600">Altere a disponibilidade em casos especiais para o Dr. {userInfo?.profile?.full_name || '...'}</p>
            </div>

            <div className="flex justify-between items-center">
                <h2 className="text-xl font-semibold">Agenda para: {displayDate}</h2>
                <Button onClick={fetchData} disabled={isLoading} variant="outline" size="sm">
                    <RefreshCw className={`mr-2 h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
                    Atualizar Agenda
                </Button>
            </div>

            <div className="grid lg:grid-cols-3 gap-6">
                <div className="lg:col-span-1">
                    <Card>
                        <CardHeader>
                            <CardTitle className="flex items-center">
                                <CalendarIcon className="mr-2 h-5 w-5" />
                                Calendário
                            </CardTitle>
                            <p className="text-sm text-gray-500">Selecione a data desejada.</p>
                        </CardHeader>
                        <CardContent className="flex justify-center p-2">
                            <Calendar
                                mode="single"
                                selected={selectedCalendarDate}
                                onSelect={setSelectedCalendarDate}
                                autoFocus
                                modifiers={{ booked: bookedDays }}
                                modifiersClassNames={{
                                    booked: "bg-blue-600 text-white aria-selected:!bg-blue-700 hover:!bg-blue-700/90",
                                }}
                                className="rounded-md border p-2"
                            />
                        </CardContent>
                    </Card>
                </div>

                <div className="lg:col-span-2 space-y-4">
                    {!selectedCalendarDate ? (
                        <p className="text-center text-lg text-gray-500">Selecione uma data no calendário.</p>
                    ) : (
                        <form className="space-y-6" onSubmit={handleSubmit}>
                            <div className="bg-white rounded-lg border border-gray-200 p-6">
                                <h2 className="text-lg font-semibold text-gray-900 mb-6">Dados da Exceção</h2>
                                <div className="space-y-6">
                                    <div className="grid md:grid-cols-2 gap-6">
                                        <div>
                                            <Label htmlFor="horarioEntrada" className="text-sm font-medium text-gray-700">
                                                Horário De Início
                                            </Label>
                                            <Input type="time" id="horarioEntrada" name="horarioEntrada" required className="mt-1" />
                                        </div>
                                        <div>
                                            <Label htmlFor="horarioSaida" className="text-sm font-medium text-gray-700">
                                                Horário De Fim
                                            </Label>
                                            <Input type="time" id="horarioSaida" name="horarioSaida" required className="mt-1" />
                                        </div>
                                    </div>

                                    <div>
                                        <Label htmlFor="tipo" className="text-sm font-medium text-gray-700">
                                            Tipo
                                        </Label>
                                        <Select onValueChange={(value) => setTipo(value as 'bloqueio' | 'liberacao')} value={tipo} required>
                                            <SelectTrigger className="mt-1">
                                                <SelectValue placeholder="Selecione o tipo" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="bloqueio">Bloqueio</SelectItem>
                                                <SelectItem value="liberacao">Liberação</SelectItem>
                                            </SelectContent>
                                        </Select>
                                    </div>
                                    <div>
                                        <Label htmlFor="reason" className="text-sm font-medium text-gray-700">
                                            Motivo
                                        </Label>
                                        <Input id="reason" name="reason" required className="mt-1" />
                                    </div>
                                </div>
                            </div>

                            <div className="flex justify-end gap-4">
                                <Link href="/doctor/disponibilidade">
                                    <Button variant="outline" type="button">Cancelar</Button>
                                </Link>
                                <Button type="submit" className="bg-green-600 hover:bg-green-700" disabled={isSubmitting}>
                                    {isSubmitting ? "Salvando..." : "Salvar Exceção"}
                                </Button>
                            </div>
                        </form>
                    )}
                </div>
            </div>
        </div>
    );
}