import { useState, useEffect } from "react";
import toast from "react-hot-toast";
import { Search, Plus, Eye, Edit, Trash2 } from "lucide-react";
import {
  appointmentService,
  type Appointment,
  patientService,
  type Patient,
  doctorService,
  type Doctor,
} from "../../services";
import { Avatar } from "../ui/Avatar";

interface AppointmentWithDetails extends Appointment {
  patient?: Patient;
  doctor?: Doctor;
}

export function SecretaryAppointmentList() {
  const [appointments, setAppointments] = useState<AppointmentWithDetails[]>(
    []
  );
  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("Todos");
  const [typeFilter, setTypeFilter] = useState("Todos");
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [patients, setPatients] = useState<Patient[]>([]);
  const [doctors, setDoctors] = useState<Doctor[]>([]);
  const [formData, setFormData] = useState({
    patient_id: "",
    doctor_id: "",
    scheduled_at: "",
    appointment_type: "presencial",
    notes: "",
  });

  const loadAppointments = async () => {
    setLoading(true);
    try {
      const data = await appointmentService.list();

      // Buscar detalhes de pacientes e médicos
      const appointmentsWithDetails = await Promise.all(
        (Array.isArray(data) ? data : []).map(async (appointment) => {
          try {
            const [patient, doctor] = await Promise.all([
              appointment.patient_id
                ? patientService.getById(appointment.patient_id)
                : null,
              appointment.doctor_id
                ? doctorService.getById(appointment.doctor_id)
                : null,
            ]);

            return {
              ...appointment,
              patient: patient || undefined,
              doctor: doctor || undefined,
            };
          } catch (error) {
            console.error("Erro ao carregar detalhes:", error);
            return appointment;
          }
        })
      );

      setAppointments(appointmentsWithDetails);
      console.log("✅ Consultas carregadas:", appointmentsWithDetails);
    } catch (error) {
      console.error("❌ Erro ao carregar consultas:", error);
      toast.error("Erro ao carregar consultas");
      setAppointments([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadAppointments();
    loadDoctorsAndPatients();
  }, []);

  const loadDoctorsAndPatients = async () => {
    try {
      const [patientsData, doctorsData] = await Promise.all([
        patientService.list(),
        doctorService.list(),
      ]);
      setPatients(Array.isArray(patientsData) ? patientsData : []);
      setDoctors(Array.isArray(doctorsData) ? doctorsData : []);
    } catch (error) {
      console.error("Erro ao carregar pacientes e médicos:", error);
    }
  };

  const handleOpenCreateModal = () => {
    setFormData({
      patient_id: "",
      doctor_id: "",
      scheduled_at: "",
      appointment_type: "presencial",
      notes: "",
    });
    setShowCreateModal(true);
  };

  const handleCreateAppointment = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!formData.patient_id || !formData.doctor_id || !formData.scheduled_at) {
      toast.error("Preencha todos os campos obrigatórios");
      return;
    }

    try {
      await appointmentService.create({
        patient_id: formData.patient_id,
        doctor_id: formData.doctor_id,
        scheduled_at: new Date(formData.scheduled_at).toISOString(),
        appointment_type: formData.appointment_type as
          | "presencial"
          | "telemedicina",
      });

      toast.success("Consulta agendada com sucesso!");
      setShowCreateModal(false);
      loadAppointments();
    } catch (error) {
      console.error("Erro ao criar consulta:", error);
      toast.error("Erro ao agendar consulta");
    }
  };

  const handleSearch = () => {
    loadAppointments();
  };

  const handleClear = () => {
    setSearchTerm("");
    setStatusFilter("Todos");
    setTypeFilter("Todos");
    loadAppointments();
  };

  const getStatusBadge = (status: string) => {
    const statusMap: Record<string, { label: string; className: string }> = {
      confirmada: {
        label: "Confirmada",
        className: "bg-green-100 text-green-700",
      },
      agendada: { label: "Agendada", className: "bg-blue-100 text-blue-700" },
      cancelada: { label: "Cancelada", className: "bg-red-100 text-red-700" },
      concluida: { label: "Concluída", className: "bg-gray-100 text-gray-700" },
    };
    const config = statusMap[status] || {
      label: status,
      className: "bg-gray-100 text-gray-700",
    };
    return (
      <span
        className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium ${config.className}`}
      >
        {config.label}
      </span>
    );
  };

  const formatDate = (dateString: string) => {
    try {
      const date = new Date(dateString);
      return date.toLocaleDateString("pt-BR", {
        day: "2-digit",
        month: "2-digit",
        year: "numeric",
      });
    } catch {
      return "—";
    }
  };

  const formatTime = (dateString: string) => {
    try {
      const date = new Date(dateString);
      return date.toLocaleTimeString("pt-BR", {
        hour: "2-digit",
        minute: "2-digit",
      });
    } catch {
      return "—";
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">Consultas</h1>
          <p className="text-gray-600 mt-1">Gerencie as consultas agendadas</p>
        </div>
        <button
          onClick={handleOpenCreateModal}
          className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
        >
          <Plus className="h-4 w-4" />
          Nova Consulta
        </button>
      </div>

      {/* Search and Filters */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6 space-y-4">
        <div className="flex gap-3">
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400" />
            <input
              type="text"
              placeholder="Buscar consultas por paciente ou médico..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"
            />
          </div>
          <button
            onClick={handleSearch}
            className="px-6 py-2.5 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
          >
            Buscar
          </button>
          <button
            onClick={handleClear}
            className="px-6 py-2.5 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
          >
            Limpar
          </button>
        </div>

        <div className="flex items-center gap-6">
          <div className="flex items-center gap-2">
            <span className="text-sm text-gray-600">Status:</span>
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="px-3 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500 focus:border-transparent"
            >
              <option>Todos</option>
              <option>Confirmada</option>
              <option>Agendada</option>
              <option>Cancelada</option>
              <option>Concluída</option>
            </select>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-sm text-gray-600">Tipo:</span>
            <select
              value={typeFilter}
              onChange={(e) => setTypeFilter(e.target.value)}
              className="px-3 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500 focus:border-transparent"
            >
              <option>Todos</option>
              <option>Presencial</option>
              <option>Telemedicina</option>
            </select>
          </div>
        </div>
      </div>

      {/* Table */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <table className="w-full">
          <thead className="bg-gray-50 border-b border-gray-200">
            <tr>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">
                Paciente
              </th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">
                Médico
              </th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">
                Data/Hora
              </th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">
                Tipo
              </th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">
                Status
              </th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">
                Ações
              </th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200">
            {loading ? (
              <tr>
                <td
                  colSpan={6}
                  className="px-6 py-12 text-center text-gray-500"
                >
                  Carregando consultas...
                </td>
              </tr>
            ) : appointments.length === 0 ? (
              <tr>
                <td
                  colSpan={6}
                  className="px-6 py-12 text-center text-gray-500"
                >
                  Nenhuma consulta encontrada
                </td>
              </tr>
            ) : (
              appointments.map((appointment) => (
                <tr
                  key={appointment.id}
                  className="hover:bg-gray-50 transition-colors"
                >
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-3">
                      <Avatar
                        src={appointment.patient}
                        name={appointment.patient?.full_name || ""}
                        size="md"
                        color="blue"
                      />
                      <div>
                        <p className="text-sm font-medium text-gray-900">
                          {appointment.patient?.full_name ||
                            "Paciente não encontrado"}
                        </p>
                        <p className="text-xs text-gray-500">
                          {appointment.patient?.email || "—"}
                        </p>
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-3">
                      <Avatar
                        src={appointment.doctor}
                        name={appointment.doctor?.full_name || ""}
                        size="md"
                        color="green"
                      />
                      <div>
                        <p className="text-sm font-medium text-gray-900">
                          {appointment.doctor?.full_name ||
                            "Médico não encontrado"}
                        </p>
                        <p className="text-xs text-gray-500">
                          {appointment.doctor?.specialty || "—"}
                        </p>
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-900">
                    {appointment.scheduled_at ? (
                      <>
                        <div className="font-medium">
                          {formatDate(appointment.scheduled_at)}
                        </div>
                        <div className="text-gray-500 text-xs">
                          {formatTime(appointment.scheduled_at)}
                        </div>
                      </>
                    ) : (
                      "—"
                    )}
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-700">
                    <span
                      className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium ${
                        appointment.appointment_type === "telemedicina"
                          ? "bg-purple-100 text-purple-700"
                          : "bg-blue-100 text-blue-700"
                      }`}
                    >
                      {appointment.appointment_type === "telemedicina"
                        ? "Telemedicina"
                        : "Presencial"}
                    </span>
                  </td>
                  <td className="px-6 py-4">
                    {getStatusBadge(appointment.status || "agendada")}
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-2">
                      <button
                        title="Visualizar"
                        className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                      >
                        <Eye className="h-4 w-4" />
                      </button>
                      <button
                        title="Editar"
                        className="p-2 text-orange-600 hover:bg-orange-50 rounded-lg transition-colors"
                      >
                        <Edit className="h-4 w-4" />
                      </button>
                      <button
                        title="Cancelar"
                        className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* Modal de Criar Consulta */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
            <div className="p-6 border-b border-gray-200">
              <h2 className="text-2xl font-bold text-gray-900">
                Nova Consulta
              </h2>
            </div>

            <form onSubmit={handleCreateAppointment} className="p-6 space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Paciente *
                  </label>
                  <select
                    value={formData.patient_id}
                    onChange={(e) =>
                      setFormData({ ...formData, patient_id: e.target.value })
                    }
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500"
                    required
                  >
                    <option value="">Selecione um paciente</option>
                    {patients.map((patient) => (
                      <option key={patient.id} value={patient.id}>
                        {patient.full_name}
                      </option>
                    ))}
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Médico *
                  </label>
                  <select
                    value={formData.doctor_id}
                    onChange={(e) =>
                      setFormData({ ...formData, doctor_id: e.target.value })
                    }
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500"
                    required
                  >
                    <option value="">Selecione um médico</option>
                    {doctors.map((doctor) => (
                      <option key={doctor.id} value={doctor.id}>
                        {doctor.full_name} - {doctor.specialty}
                      </option>
                    ))}
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Data e Hora *
                  </label>
                  <input
                    type="datetime-local"
                    value={formData.scheduled_at}
                    onChange={(e) =>
                      setFormData({ ...formData, scheduled_at: e.target.value })
                    }
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500"
                    required
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Tipo de Consulta *
                  </label>
                  <select
                    value={formData.appointment_type}
                    onChange={(e) =>
                      setFormData({
                        ...formData,
                        appointment_type: e.target.value,
                      })
                    }
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500"
                    required
                  >
                    <option value="presencial">Presencial</option>
                    <option value="telemedicina">Telemedicina</option>
                  </select>
                </div>
              </div>

              <div className="flex justify-end gap-3 pt-4">
                <button
                  type="button"
                  onClick={() => setShowCreateModal(false)}
                  className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  Cancelar
                </button>
                <button
                  type="submit"
                  className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
                >
                  Agendar Consulta
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
