"use client";

import { useEffect, useState } from "react";
import { createClient } from "@/lib/supabase/client";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { Clock, User, Phone, CheckCircle2, XCircle, Play, Loader2 } from "lucide-react";
import { format } from "date-fns";

const statusConfig: Record<string, { label: string; color: string; icon: any }> = {
  scheduled: { label: "Programada", color: "bg-blue-100 text-blue-700", icon: Clock },
  confirmed: { label: "Confirmada", color: "bg-emerald-100 text-emerald-700", icon: CheckCircle2 },
  in_progress: { label: "En consulta", color: "bg-amber-100 text-amber-700", icon: Play },
  completed: { label: "Completada", color: "bg-gray-100 text-gray-700", icon: CheckCircle2 },
  cancelled: { label: "Cancelada", color: "bg-red-100 text-red-700", icon: XCircle },
  no_show: { label: "No asistio", color: "bg-purple-100 text-purple-700", icon: XCircle },
};

export function ReceptionView() {
  const supabase = createClient();
  const [appointments, setAppointments] = useState<any[]>([]);
  const [loading, setLoading] = useState<string | null>(null);

  async function fetchToday() {
    const today = new Date().toISOString().slice(0, 10);
    const { data } = await supabase
      .from("appointments")
      .select("*, patient:patients(id, first_name, last_name, phone), doctor:users(id, full_name, color)")
      .gte("starts_at", `${today}T00:00:00`)
      .lte("starts_at", `${today}T23:59:59`)
      .order("starts_at");
    if (data) setAppointments(data);
  }

  useEffect(() => {
    fetchToday();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  async function updateStatus(id: string, status: string) {
    setLoading(id);
    await supabase.from("appointments").update({ status }).eq("id", id);
    await fetchToday();
    setLoading(null);
  }

  const active = appointments.filter(a => !["completed", "cancelled", "no_show"].includes(a.status));
  const done = appointments.filter(a => ["completed", "cancelled", "no_show"].includes(a.status));

  return (
    <div className="space-y-6">
      {/* Summary */}
      <div className="grid gap-3 sm:grid-cols-4">
        <Card><CardContent className="p-4 text-center"><div className="text-2xl font-bold">{appointments.length}</div><p className="text-xs text-muted-foreground">Total</p></CardContent></Card>
        <Card><CardContent className="p-4 text-center"><div className="text-2xl font-bold text-blue-600">{appointments.filter(a => a.status === "scheduled" || a.status === "confirmed").length}</div><p className="text-xs text-muted-foreground">Pendientes</p></CardContent></Card>
        <Card><CardContent className="p-4 text-center"><div className="text-2xl font-bold text-amber-600">{appointments.filter(a => a.status === "in_progress").length}</div><p className="text-xs text-muted-foreground">En consulta</p></CardContent></Card>
        <Card><CardContent className="p-4 text-center"><div className="text-2xl font-bold text-emerald-600">{appointments.filter(a => a.status === "completed").length}</div><p className="text-xs text-muted-foreground">Completadas</p></CardContent></Card>
      </div>

      {/* Active appointments */}
      <div className="space-y-3">
        <h3 className="font-semibold text-lg">Citas activas</h3>
        {active.length === 0 ? (
          <Card className="py-8 text-center text-muted-foreground">No hay citas activas.</Card>
        ) : (
          active.map((apt) => {
            const config = statusConfig[apt.status];
            return (
              <Card key={apt.id} className="overflow-hidden">
                <CardContent className="flex items-center justify-between gap-4 p-4">
                  <div className="flex items-center gap-4">
                    <div className="text-center min-w-[50px]">
                      <div className="text-lg font-bold">{format(new Date(apt.starts_at), "HH:mm")}</div>
                      <div className="text-xs text-muted-foreground">{format(new Date(apt.ends_at), "HH:mm")}</div>
                    </div>
                    <Separator orientation="vertical" className="h-12" />
                    <div>
                      <div className="flex items-center gap-2">
                        <span className="font-semibold">{apt.patient?.first_name} {apt.patient?.last_name}</span>
                        <Badge className={config.color} variant="secondary">{config.label}</Badge>
                      </div>
                      <div className="flex items-center gap-3 mt-1 text-xs text-muted-foreground">
                        <span className="flex items-center gap-1"><User className="h-3 w-3" />Dr. {apt.doctor?.full_name}</span>
                        {apt.patient?.phone && <span className="flex items-center gap-1"><Phone className="h-3 w-3" />{apt.patient.phone}</span>}
                      </div>
                    </div>
                  </div>
                  <div className="flex gap-2">
                    {apt.status === "scheduled" && (
                      <Button size="sm" onClick={() => updateStatus(apt.id, "confirmed")} disabled={loading === apt.id}>
                        {loading === apt.id ? <Loader2 className="h-3 w-3 animate-spin" /> : "Confirmar"}
                      </Button>
                    )}
                    {apt.status === "confirmed" && (
                      <Button size="sm" onClick={() => updateStatus(apt.id, "in_progress")} disabled={loading === apt.id}>
                        {loading === apt.id ? <Loader2 className="h-3 w-3 animate-spin" /> : "Iniciar"}
                      </Button>
                    )}
                    {apt.status === "in_progress" && (
                      <Button size="sm" onClick={() => updateStatus(apt.id, "completed")} disabled={loading === apt.id}>
                        {loading === apt.id ? <Loader2 className="h-3 w-3 animate-spin" /> : "Completar"}
                      </Button>
                    )}
                  </div>
                </CardContent>
              </Card>
            );
          })
        )}
      </div>

      {/* Done */}
      {done.length > 0 && (
        <div className="space-y-3">
          <h3 className="font-semibold text-lg text-muted-foreground">Finalizadas</h3>
          {done.map((apt) => {
            const config = statusConfig[apt.status];
            return (
              <Card key={apt.id} className="opacity-60">
                <CardContent className="flex items-center gap-4 p-4">
                  <div className="text-center min-w-[50px]">
                    <div className="text-sm font-medium">{format(new Date(apt.starts_at), "HH:mm")}</div>
                  </div>
                  <Separator orientation="vertical" className="h-8" />
                  <div className="flex items-center gap-2">
                    <span className="text-sm">{apt.patient?.first_name} {apt.patient?.last_name}</span>
                    <Badge className={config.color} variant="secondary">{config.label}</Badge>
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}
    </div>
  );
}
