import { useState, useEffect } from "react";
import toast from "react-hot-toast";
import { Search, Plus, Eye, Calendar, Edit, Trash2, X } from "lucide-react";
import { patientService, userService, type Patient } from "../../services";
import PacienteForm, { type PacienteFormData } from "../pacientes/PacienteForm";
import { Avatar } from "../ui/Avatar";

const BLOOD_TYPES = ["A+", "A-", "B+", "B-", "AB+", "AB-", "O+", "O-"];

const CONVENIOS = [
  "Particular",
  "Unimed",
  "Amil",
  "Bradesco Saúde",
  "SulAmérica",
  "Golden Cross",
];

const COUNTRY_OPTIONS = [
  { value: "55", label: "+55 🇧🇷 Brasil" },
  { value: "1", label: "+1 🇺🇸 EUA/Canadá" },
];

// Função para buscar endereço via CEP
const buscarEnderecoViaCEP = async (cep: string) => {
  try {
    const response = await fetch(`https://viacep.com.br/ws/${cep}/json/`);
    const data = await response.json();
    if (data.erro) return null;
    return {
      rua: data.logradouro,
      bairro: data.bairro,
      cidade: data.localidade,
      estado: data.uf,
      cep: data.cep,
    };
  } catch {
    return null;
  }
};

export function SecretaryPatientList() {
  const [patients, setPatients] = useState<Patient[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [insuranceFilter, setInsuranceFilter] = useState("Todos");
  const [showBirthdays, setShowBirthdays] = useState(false);
  const [showVIP, setShowVIP] = useState(false);

  // Modal states
  const [showModal, setShowModal] = useState(false);
  const [modalMode, setModalMode] = useState<"create" | "edit">("create");
  const [formData, setFormData] = useState<PacienteFormData>({
    nome: "",
    social_name: "",
    cpf: "",
    sexo: "",
    dataNascimento: "",
    email: "",
    codigoPais: "55",
    ddd: "",
    numeroTelefone: "",
    tipo_sanguineo: "",
    altura: "",
    peso: "",
    convenio: "Particular",
    numeroCarteirinha: "",
    observacoes: "",
    endereco: {
      cep: "",
      rua: "",
      numero: "",
      bairro: "",
      cidade: "",
      estado: "",
    },
  });
  const [cpfError, setCpfError] = useState<string | null>(null);
  const [cpfValidationMessage, setCpfValidationMessage] = useState<
    string | null
  >(null);

  const loadPatients = async () => {
    setLoading(true);
    try {
      const data = await patientService.list();
      console.log("✅ Pacientes carregados:", data);
      setPatients(Array.isArray(data) ? data : []);
      if (Array.isArray(data) && data.length === 0) {
        console.warn("⚠️ Nenhum paciente encontrado na API");
      }
    } catch (error) {
      console.error("❌ Erro ao carregar pacientes:", error);
      toast.error("Erro ao carregar pacientes");
      setPatients([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadPatients();
  }, []);

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

  const handleClear = () => {
    setSearchTerm("");
    setInsuranceFilter("Todos");
    setShowBirthdays(false);
    setShowVIP(false);
    loadPatients();
  };

  const handleNewPatient = () => {
    setModalMode("create");
    setFormData({
      nome: "",
      social_name: "",
      cpf: "",
      sexo: "",
      dataNascimento: "",
      email: "",
      codigoPais: "55",
      ddd: "",
      numeroTelefone: "",
      tipo_sanguineo: "",
      altura: "",
      peso: "",
      convenio: "Particular",
      numeroCarteirinha: "",
      observacoes: "",
      endereco: {
        cep: "",
        rua: "",
        numero: "",
        bairro: "",
        cidade: "",
        estado: "",
      },
    });
    setCpfError(null);
    setCpfValidationMessage(null);
    setShowModal(true);
  };

  const handleEditPatient = (patient: Patient) => {
    setModalMode("edit");
    setFormData({
      id: patient.id,
      nome: patient.full_name || "",
      social_name: patient.social_name || "",
      cpf: patient.cpf || "",
      sexo: patient.sex || "",
      dataNascimento: patient.birth_date || "",
      email: patient.email || "",
      codigoPais: "55",
      ddd: "",
      numeroTelefone: patient.phone_mobile || "",
      tipo_sanguineo: patient.blood_type || "",
      altura: patient.height_m?.toString() || "",
      peso: patient.weight_kg?.toString() || "",
      convenio: "Particular",
      numeroCarteirinha: "",
      observacoes: "",
      endereco: {
        cep: patient.cep || "",
        rua: patient.street || "",
        numero: patient.number || "",
        complemento: patient.complement || "",
        bairro: patient.neighborhood || "",
        cidade: patient.city || "",
        estado: patient.state || "",
      },
    });
    setCpfError(null);
    setCpfValidationMessage(null);
    setShowModal(true);
  };

  const handleFormChange = (patch: Partial<PacienteFormData>) => {
    setFormData((prev) => ({ ...prev, ...patch }));
  };

  const handleCpfChange = (value: string) => {
    setFormData((prev) => ({ ...prev, cpf: value }));
    setCpfError(null);
    setCpfValidationMessage(null);
  };

  const handleCepLookup = async (cep: string) => {
    const endereco = await buscarEnderecoViaCEP(cep);
    if (endereco) {
      setFormData((prev) => ({
        ...prev,
        endereco: {
          ...prev.endereco,
          ...endereco,
        },
      }));
      toast.success("Endereço encontrado!");
    } else {
      toast.error("CEP não encontrado");
    }
  };

  const handleFormSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setLoading(true);

    try {
      if (modalMode === "edit" && formData.id) {
        // Para edição, usa o endpoint antigo (PATCH /patients/:id)
        const patientData = {
          full_name: formData.nome,
          social_name: formData.social_name || null,
          cpf: formData.cpf,
          sex: formData.sexo || null,
          birth_date: formData.dataNascimento || null,
          email: formData.email,
          phone_mobile: formData.numeroTelefone,
          blood_type: formData.tipo_sanguineo || null,
          height_m: formData.altura ? parseFloat(formData.altura) : null,
          weight_kg: formData.peso ? parseFloat(formData.peso) : null,
          cep: formData.endereco.cep || null,
          street: formData.endereco.rua || null,
          number: formData.endereco.numero || null,
          complement: formData.endereco.complemento || null,
          neighborhood: formData.endereco.bairro || null,
          city: formData.endereco.cidade || null,
          state: formData.endereco.estado || null,
        };
        await patientService.update(formData.id, patientData);
        toast.success("Paciente atualizado com sucesso!");
      } else {
        // Para criação, usa o novo endpoint create-patient com validações completas
        const createData = {
          email: formData.email,
          full_name: formData.nome,
          cpf: formData.cpf,
          phone_mobile: formData.numeroTelefone,
          birth_date: formData.dataNascimento || undefined,
          address: formData.endereco.rua
            ? `${formData.endereco.rua}${
                formData.endereco.numero ? ", " + formData.endereco.numero : ""
              }${
                formData.endereco.bairro ? " - " + formData.endereco.bairro : ""
              }${
                formData.endereco.cidade ? " - " + formData.endereco.cidade : ""
              }${
                formData.endereco.estado ? "/" + formData.endereco.estado : ""
              }`
            : undefined,
        };
        await userService.createPatient(createData);
        toast.success("Paciente cadastrado com sucesso!");
      }

      setShowModal(false);
      loadPatients();
    } catch (error) {
      console.error("Erro ao salvar paciente:", error);
      toast.error("Erro ao salvar paciente");
    } finally {
      setLoading(false);
    }
  };

  const handleCancelForm = () => {
    setShowModal(false);
  };

  const getPatientColor = (
    index: number
  ): "blue" | "green" | "purple" | "orange" | "pink" | "teal" => {
    const colors: Array<
      "blue" | "green" | "purple" | "orange" | "pink" | "teal"
    > = ["blue", "green", "purple", "orange", "pink", "teal"];
    return colors[index % colors.length];
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">Pacientes</h1>
          <p className="text-gray-600 mt-1">
            Gerencie os pacientes cadastrados
          </p>
        </div>
        <button
          onClick={handleNewPatient}
          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" />
          Novo Paciente
        </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 pacientes por nome ou email..."
              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">
          <label className="flex items-center gap-2 cursor-pointer">
            <input
              type="checkbox"
              checked={showBirthdays}
              onChange={(e) => setShowBirthdays(e.target.checked)}
              className="h-4 w-4 text-green-600 border-gray-300 rounded focus:ring-green-500"
            />
            <span className="text-sm text-gray-700">
              Aniversariantes do mês
            </span>
          </label>
          <label className="flex items-center gap-2 cursor-pointer">
            <input
              type="checkbox"
              checked={showVIP}
              onChange={(e) => setShowVIP(e.target.checked)}
              className="h-4 w-4 text-green-600 border-gray-300 rounded focus:ring-green-500"
            />
            <span className="text-sm text-gray-700">Somente VIP</span>
          </label>
          <div className="flex items-center gap-2 ml-auto">
            <span className="text-sm text-gray-600">Convênio:</span>
            <select
              value={insuranceFilter}
              onChange={(e) => setInsuranceFilter(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>Particular</option>
              <option>Unimed</option>
              <option>Amil</option>
              <option>Bradesco Saúde</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">
                Próximo Atendimento
              </th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">
                Convênio
              </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={4}
                  className="px-6 py-12 text-center text-gray-500"
                >
                  Carregando pacientes...
                </td>
              </tr>
            ) : patients.length === 0 ? (
              <tr>
                <td
                  colSpan={4}
                  className="px-6 py-12 text-center text-gray-500"
                >
                  Nenhum paciente encontrado
                </td>
              </tr>
            ) : (
              patients.map((patient, index) => (
                <tr
                  key={patient.id}
                  className="hover:bg-gray-50 transition-colors"
                >
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-3">
                      <Avatar
                        src={patient}
                        name={patient.full_name || ""}
                        size="md"
                        color={getPatientColor(index)}
                      />
                      <div>
                        <p className="text-sm font-medium text-gray-900">
                          {patient.full_name}
                        </p>
                        <p className="text-sm text-gray-500">{patient.email}</p>
                        <p className="text-sm text-gray-500">
                          {patient.phone_mobile}
                        </p>
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-700">
                    {/* TODO: Buscar próximo agendamento */}—
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-700">
                    Particular
                  </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="Agendar consulta"
                        className="p-2 text-green-600 hover:bg-green-50 rounded-lg transition-colors"
                      >
                        <Calendar className="h-4 w-4" />
                      </button>
                      <button
                        onClick={() => handleEditPatient(patient)}
                        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="Deletar"
                        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 Formulário */}
      {showModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col">
            {/* Header */}
            <div className="flex items-center justify-between p-6 border-b border-gray-200">
              <h2 className="text-xl font-semibold text-gray-900">
                {modalMode === "create" ? "Novo Paciente" : "Editar Paciente"}
              </h2>
              <button
                onClick={handleCancelForm}
                className="p-2 text-gray-400 hover:text-gray-600 rounded-lg transition-colors"
              >
                <X className="h-5 w-5" />
              </button>
            </div>

            {/* Form Content */}
            <div className="flex-1 overflow-y-auto p-6">
              <PacienteForm
                mode={modalMode}
                loading={loading}
                data={formData}
                bloodTypes={BLOOD_TYPES}
                convenios={CONVENIOS}
                countryOptions={COUNTRY_OPTIONS}
                cpfError={cpfError}
                cpfValidationMessage={cpfValidationMessage}
                onChange={handleFormChange}
                onCpfChange={handleCpfChange}
                onCepLookup={handleCepLookup}
                onCancel={handleCancelForm}
                onSubmit={handleFormSubmit}
              />
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
