"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 { PaymentUpload } from "@/components/dashboard/PaymentUpload";
import { motion } from "framer-motion";
import { Calendar, CheckCircle, XCircle, User, LogOut } from "lucide-react";

type Payment = {
  id: number;
  appointmentId: number;
  amount: number;
  status: "PENDING" | "APPROVED" | "REJECTED";
  proofUrl?: string;
  rejectedReason?: string;
  createdAt: string;
};

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

export default function AssistantDashboard() {
  const router = useRouter();
  const [activeTab, setActiveTab] = useState<"agenda" | "pagos" | "pacientes">("agenda");
  const [payments, setPayments] = useState<Payment[]>([]);
  const [appointments, setAppointments] = useState<Appointment[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [selectedAppointment, setSelectedAppointment] = useState<Appointment | null>(null);
  const [rescheduleModalOpen, setRescheduleModalOpen] = useState(false);
  const [uploadAppointmentId, setUploadAppointmentId] = useState<number | null>(null);

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

  const fetchData = async () => {
    setIsLoading(true);
    try {
      if (activeTab === "agenda") {
        const res = await fetch("/api/dashboard/appointments");
        const data = await res.json();
        setAppointments(data.appointments || []);
      } else if (activeTab === "pagos") {
        const res = await fetch("/api/dashboard/payments/pending");
        const data = await res.json();
        setPayments(data.payments || []);
      }
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      setIsLoading(false);
    }
  };

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

  const handlePaymentAction = async (
    paymentId: number,
    action: "approve" | "reject",
    reason?: string
  ) => {
    try {
      const response = await fetch(`/api/payments/validate`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ paymentId, action, reason }),
      });

      if (response.ok) {
        fetchData();
      }
    } catch (error) {
      console.error("Error validating payment:", error);
    }
  };

  const handleReschedule = async (appointmentId: number) => {
    const apt = appointments.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) {
        fetchData();
        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;
    }
  };

  const handleUploadSuccess = () => {
    fetchData();
    setUploadAppointmentId(null);
  };

  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 Asistente</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>

      <nav className="border-b bg-white">
        <div className="container mx-auto px-4">
          <div className="flex space-x-8">
            {[
              { id: "agenda", label: "Agenda" },
              { id: "pagos", label: "Validación de Pagos" },
              { id: "pacientes", label: "Pacientes" },
            ].map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id as any)}
                className={`px-2 py-4 text-sm font-medium transition-colors ${
                  activeTab === tab.id
                    ? "border-b-2 border-accent text-accent"
                    : "text-secondary hover:text-primary"
                }`}
              >
                {tab.label}
              </button>
            ))}
          </div>
        </div>
      </nav>

      <main className="container mx-auto px-4 py-8">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
        >
          {activeTab === "agenda" && (
            <div>
              <h2 className="mb-6 font-serif text-2xl font-bold text-primary">Agenda Semanal</h2>
              {isLoading ? (
                <div className="flex h-64 items-center justify-center">
                  <div className="text-secondary">Cargando...</div>
                </div>
              ) : (
                <div className="space-y-4">
                  {appointments.length === 0 ? (
                    <div className="rounded-xl border border-dashed border-secondary/30 p-12 text-center">
                      <Calendar className="mx-auto mb-4 h-12 w-12 text-secondary/50" />
                      <p className="text-secondary">No hay citas programadas</p>
                    </div>
                  ) : (
                    appointments.map((apt) => (
                      <motion.div
                        key={apt.id}
                        className="rounded-xl border bg-white p-6 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">
                              <h3 className="font-serif text-lg font-semibold text-primary">
                                {apt.patient.name}
                              </h3>
                              {apt.isCrisis && (
                                <span className="rounded-full bg-red-100 px-3 py-1 text-xs font-medium text-red-700">
                                  Crisis
                                </span>
                              )}
                            </div>
                            <p className="mb-1 text-sm text-secondary">
                              <Calendar className="mr-1 inline h-4 w-4" />
                              {new Date(apt.date).toLocaleDateString("es-MX", {
                                weekday: "long",
                                year: "numeric",
                                month: "long",
                                day: "numeric",
                                hour: "2-digit",
                                minute: "2-digit",
                              })}
                            </p>
                            <p className="text-sm text-secondary">{apt.patient.phone}</p>
                          </div>
                          <div className="flex flex-col items-end gap-2">
                            <div
                              className={`rounded-full px-4 py-2 text-sm font-medium ${
                                apt.status === "confirmed"
                                  ? "bg-green-100 text-green-700"
                                  : apt.status === "cancelled"
                                    ? "bg-red-100 text-red-700"
                                    : "bg-yellow-100 text-yellow-700"
                              }`}
                            >
                              {apt.status === "confirmed"
                                ? "Confirmada"
                                : apt.status === "cancelled"
                                  ? "Cancelada"
                                  : "Pendiente"}
                            </div>
                            <Button
                              onClick={() => handleReschedule(apt.id)}
                              size="sm"
                              variant="outline"
                              className="text-xs"
                            >
                              Reacomodar
                            </Button>
                          </div>
                        </div>
                      </motion.div>
                    ))
                  )}
                </div>
              )}
            </div>
          )}

          {activeTab === "pagos" && (
            <div>
              <h2 className="mb-6 font-serif text-2xl font-bold text-primary">
                Pagos Pendientes de Validación
              </h2>
              {isLoading ? (
                <div className="flex h-64 items-center justify-center">
                  <div className="text-secondary">Cargando...</div>
                </div>
              ) : (
                <div className="space-y-4">
                  {payments.length === 0 ? (
                    <div className="rounded-xl border border-dashed border-secondary/30 p-12 text-center">
                      <CheckCircle className="mx-auto mb-4 h-12 w-12 text-green-500" />
                      <p className="text-secondary">No hay pagos pendientes</p>
                    </div>
                  ) : (
                    payments.map((payment) => (
                      <motion.div
                        key={payment.id}
                        className="rounded-xl border bg-white p-6 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">
                            <h3 className="mb-2 font-serif text-lg font-semibold text-primary">
                              Pago #{payment.id}
                            </h3>
                            <p className="mb-2 text-xl font-bold text-accent">
                              ${payment.amount.toFixed(2)}
                            </p>
                            <p className="text-sm text-secondary">Cita: #{payment.appointmentId}</p>
                            <p className="text-xs text-muted-foreground">
                              {new Date(payment.createdAt).toLocaleDateString("es-MX")}
                            </p>
                          </div>
                          <div className="flex gap-2">
                            {payment.status === "PENDING" && (
                              <>
                                <Button
                                  onClick={() => handlePaymentAction(payment.id, "approve")}
                                  size="sm"
                                  className="bg-green-500 text-white hover:bg-green-600"
                                >
                                  <CheckCircle className="mr-1 h-4 w-4" />
                                  Aprobar
                                </Button>
                                <Button
                                  onClick={() => {
                                    const reason = prompt("Motivo del rechazo:");
                                    if (reason) handlePaymentAction(payment.id, "reject", reason);
                                  }}
                                  size="sm"
                                  variant="outline"
                                  className="border-red-500 text-red-500 hover:bg-red-50"
                                >
                                  <XCircle className="mr-1 h-4 w-4" />
                                  Rechazar
                                </Button>
                              </>
                            )}
                            {payment.status === "APPROVED" && (
                              <span className="flex items-center gap-2 rounded-full bg-green-100 px-4 py-2 text-sm font-medium text-green-700">
                                <CheckCircle className="h-4 w-4" />
                                Aprobado
                              </span>
                            )}
                            {payment.status === "REJECTED" && (
                              <div className="flex flex-col gap-1 text-right">
                                <span className="flex items-center justify-end gap-2 rounded-full bg-red-100 px-4 py-2 text-sm font-medium text-red-700">
                                  <XCircle className="h-4 w-4" />
                                  Rechazado
                                </span>
                                {payment.rejectedReason && (
                                  <span className="text-xs text-red-600">
                                    {payment.rejectedReason}
                                  </span>
                                )}
                              </div>
                            )}
                          </div>
                        </div>

                        {payment.proofUrl && (
                          <div className="mt-4 border-t pt-4">
                            <a
                              href={payment.proofUrl}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="text-accent underline hover:text-accent/80"
                            >
                              Ver comprobante
                            </a>
                          </div>
                        )}
                        {!payment.proofUrl && payment.status === "PENDING" && (
                          <div className="mt-4 border-t pt-4">
                            <PaymentUpload
                              appointmentId={payment.appointmentId}
                              onUploadSuccess={handleUploadSuccess}
                            />
                          </div>
                        )}
                      </motion.div>
                    ))
                  )}
                </div>
              )}
            </div>
          )}

          {activeTab === "pacientes" && (
            <div>
              <h2 className="mb-6 font-serif text-2xl font-bold text-primary">
                Lista de Pacientes
              </h2>
              <div className="rounded-xl border border-dashed border-secondary/30 p-12 text-center">
                <User className="mx-auto mb-4 h-12 w-12 text-secondary/50" />
                <p className="text-secondary">Función de pacientes en desarrollo</p>
                <p className="mt-2 text-sm text-muted-foreground">
                  Próximamente podrás buscar y gestionar pacientes
                </p>
              </div>
            </div>
          )}
        </motion.div>
      </main>

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