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 [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: (tipo || "presencial") as "presencial" | "telemedicina",
          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 {
        const payload = {
          patient_id: pacienteId,
          doctor_id: medicoId,
          scheduled_at: iso,
          appointment_type: (tipo || "presencial") as "presencial" | "telemedicina",
          notes: observacoes || undefined,
        };
        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-50 flex items-start justify-center bg-black/40 p-4 overflow-y-auto">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-xl animate-fade-in mt-10">
        <div className="flex items-center justify-between px-4 py-3 border-b">
          <h2 className="text-lg font-semibold">{title}</h2>
          <button
            onClick={onClose}
            className="text-gray-500 hover:text-gray-700"
          >
            <X className="w-5 h-5" />
          </button>
        </div>
        <form onSubmit={handleSubmit} className="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
              </label>
              <select
                className="w-full border rounded px-2 py-2 text-sm"
                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
              </label>
              <select
                className="w-full border rounded px-2 py-2 text-sm"
                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-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Data da Consulta *
                </label>
                {medicoId ? (
                  <CalendarPicker
                    doctorId={medicoId}
                    selectedDate={selectedDate}
                    onSelectDate={(date) => {
                      setSelectedDate(date);
                      setSelectedTime(""); // Resetar horário ao mudar data
                    }}
                  />
                ) : (
                  <div className="bg-gray-50 border border-gray-200 rounded-lg p-4 text-center text-gray-500 text-sm">
                    Selecione um médico primeiro para ver a disponibilidade
                  </div>
                )}
              </div>

              {/* Seletor de Horários */}
              {selectedDate && medicoId && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Horário * {selectedTime && <span className="text-blue-600 font-semibold">({selectedTime})</span>}
                  </label>
                  <AvailableSlotsPicker
                    doctorId={medicoId}
                    date={selectedDate}
                    onSelect={(time) => {
                      setSelectedTime(time);
                    }}
                  />
                </div>
              )}
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Tipo
              </label>
              <input
                list="tipos-consulta"
                className="w-full border rounded px-2 py-2 text-sm"
                value={tipo}
                onChange={(e) => setTipo(e.target.value)}
                placeholder="Ex: Retorno"
              />
              <datalist id="tipos-consulta">
                {TIPO_SUGESTOES.map((t) => (
                  <option key={t} value={t} />
                ))}
              </datalist>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Motivo
              </label>
              <input
                className="w-full border rounded px-2 py-2 text-sm"
                value={motivo}
                onChange={(e) => setMotivo(e.target.value)}
                placeholder="Motivo principal"
              />
            </div>
            <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 rounded px-2 py-2 text-sm resize-y min-h-[80px]"
                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
                </label>
                <select
                  className="w-full border rounded px-2 py-2 text-sm"
                  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-xs text-gray-500 flex items-center">
              <Loader2 className="w-4 h-4 mr-1 animate-spin" /> Carregando
              listas...
            </p>
          )}
          <div className="flex justify-end gap-2 pt-2 border-t">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-sm rounded border border-gray-300 text-gray-700 hover:bg-gray-50"
            >
              Cancelar
            </button>
            <button
              type="submit"
              disabled={saving}
              className="px-4 py-2 text-sm rounded bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-60 flex items-center"
            >
              {saving && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}{" "}
              {editing ? "Salvar alterações" : "Criar consulta"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default ConsultaModal;
