"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { RescheduleModal } from "@/components/dashboard/RescheduleModal";
import { motion } from "framer-motion";
import { Calendar, FileText, LogOut } from "lucide-react";

type Patient = {
  phone: string;
  name: string;
  birthdate: string;
  email?: string;
  status: string;
};

type ClinicalNote = {
  id: number;
  patientId: string;
  content: string;
  tags?: string;
  createdAt: string;
};

type Appointment = {
  id: number;
  patientPhone: string;
  date: string;
  status: string;
  isCrisis: boolean;
  patient: {
    name: string;
    phone: string;
  };
  payment?: {
    id: number;
    amount: number;
    status: string;
  };
};

export default function TherapistDashboard() {
  const router = useRouter();
  const [selectedPatient, setSelectedPatient] = useState<Patient | null>(null);
  const [patientNotes, setPatientNotes] = useState<ClinicalNote[]>([]);
  const [patientAppointments, setPatientAppointments] = useState<Appointment[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedAppointment, setSelectedAppointment] = useState<Appointment | null>(null);
  const [rescheduleModalOpen, setRescheduleModalOpen] = useState(false);

  useEffect(() => {
    if (selectedPatient) {
      fetchPatientData(selectedPatient.phone);
    }
  }, [selectedPatient]);

  const fetchPatientData = async (phone: string) => {
    setIsLoading(true);
    try {
      const [notesRes, appointmentsRes] = await Promise.all([
        fetch(`/api/dashboard/patients/${phone}/notes`),
        fetch(`/api/dashboard/patients/${phone}/appointments`),
      ]);

      const notesData = await notesRes.json();
      const appointmentsData = await appointmentsRes.json();

      setPatientNotes(notesData.notes || []);
      setPatientAppointments(appointmentsData.appointments || []);
    } catch (error) {
      console.error("Error fetching patient data:", error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleLogout = async () => {
    await fetch("/api/auth/logout", { method: "POST" });
    router.push("/login");
  };

  const handleReschedule = async (appointmentId: number) => {
    const apt = patientAppointments.find((a) => a.id === appointmentId);
    if (apt) {
      setSelectedAppointment(apt);
      setRescheduleModalOpen(true);
    }
  };

  const handleRescheduleConfirm = async (newDate: Date, reason?: string) => {
    try {
      const response = await fetch("/api/calendar/reschedule", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          appointmentId: selectedAppointment?.id,
          newDate: newDate.toISOString(),
          reason,
        }),
      });

      if (response.ok) {
        if (selectedPatient) {
          fetchPatientData(selectedPatient.phone);
        }
        setRescheduleModalOpen(false);
        setSelectedAppointment(null);
      } else {
        const data = await response.json();
        throw new Error(data.message || "Error al reacomodar la cita");
      }
    } catch (error: any) {
      throw error;
    }
  };

  return (
    <div className="min-h-screen bg-background">
      <header className="bg-primary text-white">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="font-serif text-2xl font-bold">Dashboard Terapeuta</h1>
              <p className="text-sm text-white/70">Gloria Niño</p>
            </div>
            <Button
              onClick={handleLogout}
              variant="outline"
              className="border-white text-white hover:bg-white hover:text-primary"
            >
              <LogOut className="mr-2 h-4 w-4" />
              Salir
            </Button>
          </div>
        </div>
      </header>

      <div className="container mx-auto px-4 py-8">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
        >
          {!selectedPatient ? (
            <div>
              <h2 className="mb-6 font-serif text-2xl font-bold text-primary">
                Expedientes de Pacientes
              </h2>
              <div className="rounded-xl border border-dashed border-secondary/30 p-12 text-center">
                <FileText className="mx-auto mb-4 h-12 w-12 text-secondary/50" />
                <p className="text-secondary">Selecciona un paciente para ver su expediente</p>
                <p className="mt-2 text-sm text-muted-foreground">
                  Próximamente podrás buscar y seleccionar pacientes
                </p>
              </div>
            </div>
          ) : (
            <div>
              <Button onClick={() => setSelectedPatient(null)} variant="ghost" className="mb-4">
                ← Volver a lista de pacientes
              </Button>

              <div className="mb-8 rounded-xl border bg-white p-6 shadow-sm">
                <h2 className="mb-4 font-serif text-2xl font-bold text-primary">
                  {selectedPatient.name}
                </h2>
                <div className="grid gap-4 md:grid-cols-2">
                  <div>
                    <p className="mb-1 text-sm text-secondary">Teléfono</p>
                    <p className="font-medium">{selectedPatient.phone}</p>
                  </div>
                  <div>
                    <p className="mb-1 text-sm text-secondary">Email</p>
                    <p className="font-medium">{selectedPatient.email || "No registrado"}</p>
                  </div>
                  <div>
                    <p className="mb-1 text-sm text-secondary">Fecha de Nacimiento</p>
                    <p className="font-medium">
                      {new Date(selectedPatient.birthdate).toLocaleDateString("es-MX")}
                    </p>
                  </div>
                  <div>
                    <p className="mb-1 text-sm text-secondary">Estado</p>
                    <span
                      className={`rounded-full px-3 py-1 text-sm font-medium ${
                        selectedPatient.status === "active"
                          ? "bg-green-100 text-green-700"
                          : "bg-gray-100 text-gray-700"
                      }`}
                    >
                      {selectedPatient.status === "active" ? "Activo" : "Inactivo"}
                    </span>
                  </div>
                </div>
              </div>

              <div className="grid gap-8 lg:grid-cols-2">
                <div>
                  <h3 className="mb-4 font-serif text-xl font-bold text-primary">Notas Clínicas</h3>
                  {isLoading ? (
                    <div className="flex h-32 items-center justify-center">
                      <div className="text-secondary">Cargando...</div>
                    </div>
                  ) : (
                    <div className="space-y-4">
                      {patientNotes.length === 0 ? (
                        <div className="rounded-lg border border-dashed p-6 text-center">
                          <p className="text-sm text-secondary">
                            No hay notas clínicas registradas
                          </p>
                        </div>
                      ) : (
                        patientNotes.map((note) => (
                          <motion.div
                            key={note.id}
                            className="rounded-lg border bg-white p-4 shadow-sm"
                            initial={{ opacity: 0, x: -20 }}
                            animate={{ opacity: 1, x: 0 }}
                            transition={{ duration: 0.3 }}
                          >
                            <div className="mb-2 flex items-center justify-between">
                              <span className="text-xs text-muted-foreground">
                                {new Date(note.createdAt).toLocaleDateString("es-MX")}
                              </span>
                              {note.tags && (
                                <span className="rounded bg-accent/10 px-2 py-1 text-xs text-accent">
                                  {note.tags}
                                </span>
                              )}
                            </div>
                            <p className="whitespace-pre-wrap text-secondary">{note.content}</p>
                          </motion.div>
                        ))
                      )}
                    </div>
                  )}
                </div>

                <div>
                  <h3 className="mb-4 font-serif text-xl font-bold text-primary">Citas</h3>
                  {isLoading ? (
                    <div className="flex h-32 items-center justify-center">
                      <div className="text-secondary">Cargando...</div>
                    </div>
                  ) : (
                    <div className="space-y-4">
                      {patientAppointments.length === 0 ? (
                        <div className="rounded-lg border border-dashed p-6 text-center">
                          <p className="text-sm text-secondary">No hay citas registradas</p>
                        </div>
                      ) : (
                        patientAppointments.map((apt) => (
                          <motion.div
                            key={apt.id}
                            className="rounded-lg border bg-white p-4 shadow-sm"
                            initial={{ opacity: 0, x: -20 }}
                            animate={{ opacity: 1, x: 0 }}
                            transition={{ duration: 0.3 }}
                          >
                            <div className="flex items-start justify-between">
                              <div className="flex-1">
                                <div className="mb-2 flex items-center gap-2">
                                  <p className="font-medium text-primary">
                                    {new Date(apt.date).toLocaleDateString("es-MX", {
                                      weekday: "long",
                                      year: "numeric",
                                      month: "long",
                                      day: "numeric",
                                      hour: "2-digit",
                                      minute: "2-digit",
                                    })}
                                  </p>
                                  {apt.isCrisis && (
                                    <span className="rounded-full bg-red-100 px-2 py-1 text-xs font-medium text-red-700">
                                      Crisis
                                    </span>
                                  )}
                                </div>
                                <p className="text-sm text-muted-foreground">{apt.status}</p>
                                {apt.payment && (
                                  <p className="mt-2 text-sm">
                                    <span className="font-medium text-accent">
                                      Pago: ${apt.payment.amount.toFixed(2)}
                                    </span>
                                    <span
                                      className={`ml-2 rounded px-2 py-1 text-xs ${
                                        apt.payment.status === "APPROVED"
                                          ? "bg-green-100 text-green-700"
                                          : apt.payment.status === "REJECTED"
                                            ? "bg-red-100 text-red-700"
                                            : "bg-yellow-100 text-yellow-700"
                                      }`}
                                    >
                                      {apt.payment.status === "APPROVED"
                                        ? "Aprobado"
                                        : apt.payment.status === "REJECTED"
                                          ? "Rechazado"
                                          : "Pendiente"}
                                    </span>
                                  </p>
                                )}
                              </div>
                              <div className="flex flex-col items-end gap-2">
                                <Calendar className="h-5 w-5 text-secondary/50" />
                                <Button
                                  onClick={() => handleReschedule(apt.id)}
                                  size="sm"
                                  variant="outline"
                                  className="text-xs"
                                >
                                  Reacomodar
                                </Button>
                              </div>
                            </div>
                          </motion.div>
                        ))
                      )}
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}
        </motion.div>
      </div>

      {rescheduleModalOpen && selectedAppointment && selectedPatient && (
        <RescheduleModal
          isOpen={rescheduleModalOpen}
          onClose={() => {
            setRescheduleModalOpen(false);
            setSelectedAppointment(null);
          }}
          onConfirm={handleRescheduleConfirm}
          currentDate={new Date(selectedAppointment.date)}
          patientName={selectedPatient.name}
        />
      )}
    </div>
  );
}
