import React, { useEffect, useState, useCallback } from "react";
import { X, Loader2 } from "lucide-react";
import {
  appointmentService,
  patientService,
  doctorService,
  type Appointment,
  type Patient,
  type Doctor,
} from "../../services";
import { useAuth } from "../../hooks/useAuth";
import { CalendarPicker } from "../agenda/CalendarPicker";
import AvailableSlotsPicker from "../agenda/AvailableSlotsPicker";

// Type aliases para compatibilidade com código antigo
type Consulta = Appointment & {
  pacienteId?: string;
  medicoId?: string;
  dataHora?: string;
  observacoes?: string;
};
type Paciente = Patient;
type Medico = Doctor;

interface ConsultaModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSaved: (c: Consulta) => void;
  editing?: Consulta | null;
  defaultPacienteId?: string;
  defaultMedicoId?: string;
  lockPaciente?: boolean; // quando abrir a partir do prontuário
  lockMedico?: boolean; // quando médico logado não deve mudar
}

const TIPO_SUGESTOES = [
  "Primeira consulta",
  "Retorno",
  "Acompanhamento",
  "Exame",
  "Telemedicina",
];

const ConsultaModal: React.FC<ConsultaModalProps> = ({
  isOpen,
  onClose,
  onSaved,
  editing,
  defaultPacienteId,
  defaultMedicoId,
  lockPaciente = false,
  lockMedico = false,
}) => {
  const { user } = useAuth();

  const [pacientes, setPacientes] = useState<Paciente[]>([]);
  const [medicos, setMedicos] = useState<Medico[]>([]);
  const [loadingLists, setLoadingLists] = useState(false);

  const [pacienteId, setPacienteId] = useState("");
  const [medicoId, setMedicoId] = useState("");
  const [selectedDate, setSelectedDate] = useState<string>("");
  const [selectedTime, setSelectedTime] = useState<string>("");
  const [tipo, setTipo] = useState("");
  const [appointmentType, setAppointmentType] = useState<
    "presencial" | "telemedicina"
  >("presencial");
  const [motivo, setMotivo] = useState("");
  const [observacoes, setObservacoes] = useState("");
  const [status, setStatus] = useState<string>("requested");

  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Load supporting lists
  useEffect(() => {
    if (!isOpen) return;
    let active = true;
    (async () => {
      try {
        setLoadingLists(true);
        const [patients, doctors] = await Promise.all([
          patientService.list().catch(() => []),
          doctorService.list().catch(() => []),
        ]);
        if (!active) return;
        setPacientes(patients);
        setMedicos(doctors);
      } finally {
        if (active) setLoadingLists(false);
      }
    })();
    return () => {
      active = false;
    };
  }, [isOpen]);

  // Initialize form when opening / editing changes
  useEffect(() => {
    if (!isOpen) return;
    if (editing) {
      setPacienteId(editing.patient_id || "");
      setMedicoId(editing.doctor_id || "");
      // Convert ISO to date and time
      try {
        const d = new Date(editing.scheduled_at);
        const dateStr = d.toISOString().split("T")[0]; // YYYY-MM-DD
        const timeStr = `${d.getHours().toString().padStart(2, "0")}:${d
          .getMinutes()
          .toString()
          .padStart(2, "0")}`;
        setSelectedDate(dateStr);
        setSelectedTime(timeStr);
      } catch {
        setSelectedDate("");
        setSelectedTime("");
      }
      setTipo(editing.appointment_type || "");
      setObservacoes(editing.notes || "");
      setStatus(editing.status || "requested");
    } else {
      setPacienteId(defaultPacienteId || "");
      setMedicoId(defaultMedicoId || "");
      setSelectedDate("");
      setSelectedTime("");
      setTipo("");
      setMotivo("");
      setObservacoes("");
      setStatus("requested");
    }
    setError(null);
    setSaving(false);
  }, [isOpen, editing, defaultPacienteId, defaultMedicoId, user]);

  const closeOnEsc = useCallback(
    (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    },
    [onClose]
  );

  useEffect(() => {
    if (!isOpen) return;
    window.addEventListener("keydown", closeOnEsc);
    return () => window.removeEventListener("keydown", closeOnEsc);
  }, [isOpen, closeOnEsc]);

  if (!isOpen) return null;

  const validate = (): boolean => {
    if (!pacienteId) {
      setError("Selecione um paciente.");
      return false;
    }
    if (!medicoId) {
      setError("Selecione um médico.");
      return false;
    }
    if (!selectedDate || !selectedTime) {
      setError("Selecione data e horário da consulta.");
      return false;
    }
    return true;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;
    setSaving(true);
    setError(null);
    try {
      // Combinar data e horário no formato ISO
      const datetime = `${selectedDate}T${selectedTime}:00`;
      const iso = new Date(datetime).toISOString();

      if (editing) {
        const payload = {
          scheduled_at: iso,
          appointment_type: appointmentType,
          notes: observacoes || undefined,
          status: status as
            | "requested"
            | "confirmed"
            | "checked_in"
            | "in_progress"
            | "completed"
            | "cancelled"
            | "no_show",
        };
        const updated = await appointmentService.update(editing.id, payload);
        onSaved(updated);
      } else {
        // Buscar user ID do localStorage ou context
        const userStr = localStorage.getItem("mediconnect_user");
        let userId = user?.id;

        if (!userId && userStr) {
          try {
            const userData = JSON.parse(userStr);
            userId = userData.id;
          } catch (e) {
            console.warn("Erro ao parsear user do localStorage");
          }
        }

        // Payload conforme documentação da API Supabase
        const payload = {
          doctor_id: medicoId,
          patient_id: pacienteId,
          scheduled_at: iso,
          duration_minutes: 30,
          created_by: userId,
        };
        const created = await appointmentService.create(payload);
        onSaved(created);
      }
      onClose();
    } catch (err) {
      const msg = err instanceof Error ? err.message : "Erro ao salvar";
      setError(msg);
    } finally {
      setSaving(false);
    }
  };

  const title = editing ? "Editar Consulta" : "Nova Consulta";

  return (
    <div className="fixed inset-0 z-[10000] flex items-center justify-center bg-black/50 p-4 overflow-y-auto">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-2xl my-auto max-h-[95vh] flex flex-col">
        <div className="flex items-center justify-between px-4 py-3 border-b bg-gradient-to-r from-blue-50 to-indigo-50 flex-shrink-0">
          <h2 className="text-lg font-semibold text-gray-800">{title}</h2>
          <button
            onClick={onClose}
            className="text-gray-500 hover:text-gray-700 p-1 hover:bg-gray-100 rounded transition-colors"
            aria-label="Fechar"
          >
            <X className="w-5 h-5" />
          </button>
        </div>
        <form
          onSubmit={handleSubmit}
          className="flex-1 overflow-y-auto p-4 space-y-4"
        >
          {error && (
            <div className="bg-red-50 border border-red-200 text-red-700 px-3 py-2 rounded text-sm">
              {error}
            </div>
          )}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Paciente <span className="text-red-500">*</span>
              </label>
              <select
                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                value={pacienteId}
                onChange={(e) => setPacienteId(e.target.value)}
                disabled={lockPaciente || !!editing}
              >
                <option value="">Selecione...</option>
                {pacientes.map((p) => (
                  <option key={p.id} value={p.id}>
                    {p.full_name}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Médico <span className="text-red-500">*</span>
              </label>
              <select
                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                value={medicoId}
                onChange={(e) => setMedicoId(e.target.value)}
                disabled={lockMedico || !!editing}
              >
                <option value="">Selecione...</option>
                {medicos.map((m) => (
                  <option key={m.id} value={m.id}>
                    {m.full_name} - {m.specialty}
                  </option>
                ))}
              </select>
            </div>
            {/* Calendário Visual */}
            <div className="md:col-span-2 space-y-3">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Data da Consulta <span className="text-red-500">*</span>
                </label>
                {medicoId ? (
                  <div className="bg-gray-50 border border-gray-200 rounded-lg p-3">
                    <CalendarPicker
                      doctorId={medicoId}
                      selectedDate={selectedDate}
                      onSelectDate={(date) => {
                        setSelectedDate(date);
                        setSelectedTime("");
                      }}
                    />
                  </div>
                ) : (
                  <div className="bg-gray-50 border border-gray-200 rounded-lg p-4 text-center text-gray-500 text-sm">
                    <p className="font-medium">📅 Calendário Indisponível</p>
                    <p className="text-xs mt-1">Selecione um médico primeiro</p>
                  </div>
                )}
              </div>

              {/* Seletor de Horários */}
              {selectedDate && medicoId && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Horário <span className="text-red-500">*</span>
                    {selectedTime && (
                      <span className="text-blue-600 font-semibold ml-2">
                        ({selectedTime})
                      </span>
                    )}
                  </label>
                  <div className="bg-gray-50 border border-gray-200 rounded-lg p-3">
                    <AvailableSlotsPicker
                      doctorId={medicoId}
                      date={selectedDate}
                      onSelect={(time) => {
                        setSelectedTime(time);
                      }}
                    />
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Linha com Tipo de Consulta e Motivo - Fora do grid para ocupar largura total */}
          <div className="grid grid-cols-1 md:grid-cols-[auto_1fr] gap-4 items-end">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Tipo de Consulta <span className="text-red-500">*</span>
              </label>
              <div className="flex gap-2">
                <label className="flex items-center justify-center gap-2 cursor-pointer px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors has-[:checked]:border-blue-500 has-[:checked]:bg-blue-50 whitespace-nowrap">
                  <input
                    type="radio"
                    value="presencial"
                    checked={appointmentType === "presencial"}
                    onChange={(e) =>
                      setAppointmentType(e.target.value as "presencial")
                    }
                    className="w-4 h-4 text-blue-600"
                  />
                  <span className="text-sm font-medium">Presencial</span>
                </label>
                <label className="flex items-center justify-center gap-2 cursor-pointer px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors has-[:checked]:border-blue-500 has-[:checked]:bg-blue-50 whitespace-nowrap">
                  <input
                    type="radio"
                    value="telemedicina"
                    checked={appointmentType === "telemedicina"}
                    onChange={(e) =>
                      setAppointmentType(e.target.value as "telemedicina")
                    }
                    className="w-4 h-4 text-blue-600"
                  />
                  <span className="text-sm font-medium">Telemedicina</span>
                </label>
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Motivo
              </label>
              <input
                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                value={motivo}
                onChange={(e) => setMotivo(e.target.value)}
                placeholder="Motivo principal"
              />
            </div>
          </div>

          {editing && (
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Status
              </label>
              <select
                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                value={status}
                onChange={(e) => setStatus(e.target.value)}
              >
                <option value="requested">Solicitado</option>
                <option value="confirmed">Confirmado</option>
                <option value="checked_in">Check-in</option>
                <option value="in_progress">Em Andamento</option>
                <option value="completed">Concluído</option>
                <option value="cancelled">Cancelado</option>
                <option value="no_show">Não Compareceu</option>
              </select>
            </div>
          )}

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="md:col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Observações
              </label>
              <textarea
                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm resize-y min-h-[80px] focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                value={observacoes}
                onChange={(e) => setObservacoes(e.target.value)}
                placeholder="Notas internas, preparação, etc"
              />
            </div>
            {editing && (
              <div className="md:col-span-2">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Status <span className="text-red-500">*</span>
                </label>
                <select
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  value={status}
                  onChange={(e) => setStatus(e.target.value)}
                >
                  <option value="agendada">Agendada</option>
                  <option value="confirmada">Confirmada</option>
                  <option value="cancelada">Cancelada</option>
                  <option value="realizada">Realizada</option>
                  <option value="faltou">Faltou</option>
                </select>
              </div>
            )}
          </div>
          {loadingLists && (
            <p className="text-sm text-gray-500 flex items-center bg-blue-50 py-2 px-3 rounded">
              <Loader2 className="w-4 h-4 mr-2 animate-spin" /> Carregando
              listas...
            </p>
          )}
        </form>
        <div className="flex gap-2 px-4 py-3 border-t bg-gray-50 flex-shrink-0">
          <button
            type="button"
            onClick={onClose}
            className="flex-1 px-4 py-2 text-sm rounded-lg border-2 border-gray-300 text-gray-700 hover:bg-gray-100 font-medium"
          >
            Cancelar
          </button>
          <button
            type="submit"
            disabled={saving}
            onClick={handleSubmit}
            className="flex-1 px-4 py-2 text-sm rounded-lg bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-60 disabled:cursor-not-allowed flex items-center justify-center font-medium"
          >
            {saving && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
            {editing ? "Salvar alterações" : "Criar consulta"}
          </button>
        </div>
      </div>
    </div>
  );
};

export default ConsultaModal;
