"use client";

import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Calendar, Clock, X } from "lucide-react";

interface RescheduleModalProps {
  isOpen: boolean;
  onClose: () => void;
  onConfirm: (newDate: Date, reason?: string) => Promise<void>;
  currentDate: Date;
  patientName: string;
}

export function RescheduleModal({
  isOpen,
  onClose,
  onConfirm,
  currentDate,
  patientName,
}: RescheduleModalProps) {
  const [newDate, setNewDate] = useState("");
  const [newTime, setNewTime] = useState("");
  const [reason, setReason] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState("");

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");

    if (!newDate || !newTime) {
      setError("Por favor selecciona una fecha y hora");
      return;
    }

    const combinedDateTime = new Date(`${newDate}T${newTime}`);

    if (isNaN(combinedDateTime.getTime())) {
      setError("Fecha u hora inválida");
      return;
    }

    const now = new Date();
    if (combinedDateTime <= now) {
      setError("La nueva cita debe ser en el futuro");
      return;
    }

    setIsLoading(true);
    try {
      await onConfirm(combinedDateTime, reason || undefined);
      onClose();
      setNewDate("");
      setNewTime("");
      setReason("");
    } catch (err: any) {
      setError(err.message || "Error al reacomodar la cita");
    } finally {
      setIsLoading(false);
    }
  };

  const minDate = new Date().toISOString().split("T")[0];

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={onClose}
            className="fixed inset-0 z-50 bg-black/50"
          />

          <motion.div
            initial={{ opacity: 0, scale: 0.95, y: 20 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.95, y: 20 }}
            className="fixed left-1/2 top-1/2 z-50 w-full max-w-lg -translate-x-1/2 -translate-y-1/2 rounded-2xl bg-white p-6 shadow-2xl"
          >
            <div className="mb-6 flex items-center justify-between">
              <div>
                <h2 className="font-serif text-2xl font-bold text-primary">Reacomodar Cita</h2>
                <p className="mt-1 text-sm text-secondary">{patientName}</p>
              </div>
              <button
                onClick={onClose}
                className="rounded-full p-2 text-secondary transition-colors hover:bg-gray-100"
              >
                <X size={20} />
              </button>
            </div>

            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label className="mb-2 block text-sm font-medium text-secondary">
                  Fecha Actual
                </label>
                <div className="flex items-center gap-2 rounded-lg bg-gray-50 p-3">
                  <Calendar className="h-5 w-5 text-accent" />
                  <span className="text-sm font-medium text-primary">
                    {currentDate.toLocaleDateString("es-MX", {
                      weekday: "long",
                      year: "numeric",
                      month: "long",
                      day: "numeric",
                      hour: "2-digit",
                      minute: "2-digit",
                    })}
                  </span>
                </div>
              </div>

              <div className="grid gap-4 sm:grid-cols-2">
                <div>
                  <label
                    htmlFor="newDate"
                    className="mb-2 block text-sm font-medium text-secondary"
                  >
                    Nueva Fecha
                  </label>
                  <div className="relative">
                    <Calendar className="absolute left-3 top-1/2 h-5 w-5 -translate-y-1/2 text-secondary" />
                    <Input
                      id="newDate"
                      type="date"
                      value={newDate}
                      onChange={(e) => setNewDate(e.target.value)}
                      min={minDate}
                      required
                      className="pl-10"
                    />
                  </div>
                </div>

                <div>
                  <label
                    htmlFor="newTime"
                    className="mb-2 block text-sm font-medium text-secondary"
                  >
                    Nueva Hora
                  </label>
                  <div className="relative">
                    <Clock className="absolute left-3 top-1/2 h-5 w-5 -translate-y-1/2 text-secondary" />
                    <Input
                      id="newTime"
                      type="time"
                      value={newTime}
                      onChange={(e) => setNewTime(e.target.value)}
                      required
                      className="pl-10"
                    />
                  </div>
                </div>
              </div>

              <div>
                <label htmlFor="reason" className="mb-2 block text-sm font-medium text-secondary">
                  Razón (opcional)
                </label>
                <textarea
                  id="reason"
                  value={reason}
                  onChange={(e) => setReason(e.target.value)}
                  placeholder="Motivo del cambio..."
                  rows={3}
                  className="w-full rounded-lg border border-gray-200 p-3 text-sm focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/20"
                />
              </div>

              {error && (
                <div className="rounded-lg bg-red-50 p-3 text-sm text-red-600">{error}</div>
              )}

              <div className="flex gap-3 pt-4">
                <Button
                  type="button"
                  variant="outline"
                  onClick={onClose}
                  className="flex-1"
                  disabled={isLoading}
                >
                  Cancelar
                </Button>
                <Button
                  type="submit"
                  className="flex-1 bg-accent hover:bg-accent/90"
                  disabled={isLoading}
                >
                  {isLoading ? "Procesando..." : "Confirmar"}
                </Button>
              </div>
            </form>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}
