"use client";

import { useState } from "react";
import { createClient } from "@/lib/supabase/client";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { User, Clock, Calendar, FileText, Phone, Loader2 } from "lucide-react";
import { format } from "date-fns";
import { es } from "date-fns/locale";

const statusLabels: Record<string, string> = {
  scheduled: "Programada",
  confirmed: "Confirmada",
  in_progress: "En consulta",
  completed: "Completada",
  cancelled: "Cancelada",
  no_show: "No asistio",
};

const statusColors: Record<string, string> = {
  scheduled: "bg-blue-100 text-blue-700",
  confirmed: "bg-emerald-100 text-emerald-700",
  in_progress: "bg-amber-100 text-amber-700",
  completed: "bg-gray-100 text-gray-700",
  cancelled: "bg-red-100 text-red-700",
  no_show: "bg-purple-100 text-purple-700",
};

const transitions: Record<string, { label: string; status: string; variant: "default" | "outline" | "destructive" }[]> = {
  scheduled: [
    { label: "Confirmar", status: "confirmed", variant: "default" },
    { label: "Cancelar", status: "cancelled", variant: "destructive" },
  ],
  confirmed: [
    { label: "Iniciar consulta", status: "in_progress", variant: "default" },
    { label: "No asistio", status: "no_show", variant: "outline" },
    { label: "Cancelar", status: "cancelled", variant: "destructive" },
  ],
  in_progress: [
    { label: "Completar", status: "completed", variant: "default" },
  ],
};

interface Props {
  appointment: any;
  onStatusChange: () => void;
}

export function AppointmentDetail({ appointment, onStatusChange }: Props) {
  const supabase = createClient();
  const [loading, setLoading] = useState<string | null>(null);

  async function handleStatusChange(newStatus: string) {
    setLoading(newStatus);
    await supabase.from("appointments").update({ status: newStatus }).eq("id", appointment.id);
    setLoading(null);
    onStatusChange();
  }

  const startDate = new Date(appointment.starts_at);
  const endDate = new Date(appointment.ends_at);
  const available = transitions[appointment.status] || [];

  return (
    <div className="space-y-4">
      {/* Status */}
      <div className="flex items-center justify-between">
        <Badge className={statusColors[appointment.status]}>
          {statusLabels[appointment.status]}
        </Badge>
        <Badge variant="outline">
          {appointment.type === "primera_vez" ? "Primera vez" : appointment.type === "urgencia" ? "Urgencia" : "Seguimiento"}
        </Badge>
      </div>

      <Separator />

      {/* Patient */}
      <div className="flex items-center gap-3">
        <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10 text-primary font-semibold text-sm">
          {appointment.patient?.first_name?.[0]}{appointment.patient?.last_name?.[0]}
        </div>
        <div>
          <p className="font-semibold">{appointment.patient?.first_name} {appointment.patient?.last_name}</p>
          {appointment.patient?.phone && (
            <p className="text-xs text-muted-foreground flex items-center gap-1"><Phone className="h-3 w-3" />{appointment.patient.phone}</p>
          )}
        </div>
      </div>

      {/* Details */}
      <div className="space-y-2 text-sm">
        <div className="flex items-center gap-2 text-muted-foreground">
          <User className="h-4 w-4" />
          <span>Dr. {appointment.doctor?.full_name}</span>
        </div>
        <div className="flex items-center gap-2 text-muted-foreground">
          <Calendar className="h-4 w-4" />
          <span>{format(startDate, "EEEE d 'de' MMMM, yyyy", { locale: es })}</span>
        </div>
        <div className="flex items-center gap-2 text-muted-foreground">
          <Clock className="h-4 w-4" />
          <span>{format(startDate, "HH:mm")} - {format(endDate, "HH:mm")}</span>
        </div>
        {appointment.reason && (
          <div className="flex items-start gap-2 text-muted-foreground">
            <FileText className="mt-0.5 h-4 w-4" />
            <span>{appointment.reason}</span>
          </div>
        )}
      </div>

      {/* Actions */}
      {available.length > 0 && (
        <>
          <Separator />
          <div className="flex flex-wrap gap-2">
            {available.map((action) => (
              <Button
                key={action.status}
                variant={action.variant}
                size="sm"
                disabled={loading !== null}
                onClick={() => handleStatusChange(action.status)}
              >
                {loading === action.status && <Loader2 className="mr-1 h-3 w-3 animate-spin" />}
                {action.label}
              </Button>
            ))}
          </div>
        </>
      )}
    </div>
  );
}
