import { useState, useEffect } from "react";
import toast from "react-hot-toast";
import { Search, FileText, Download, Plus } from "lucide-react";
import {
  reportService,
  type Report,
  patientService,
  type Patient,
} from "../../services";

export function SecretaryReportList() {
  const [reports, setReports] = useState<Report[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [typeFilter, setTypeFilter] = useState("Todos");
  const [periodFilter, setPeriodFilter] = useState("Todos");
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [patients, setPatients] = useState<Patient[]>([]);
  const [formData, setFormData] = useState({
    patient_id: "",
    exam: "",
    diagnosis: "",
    conclusion: "",
  });

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

  const loadPatients = async () => {
    try {
      const data = await patientService.list();
      setPatients(Array.isArray(data) ? data : []);
    } catch (error) {
      console.error("Erro ao carregar pacientes:", error);
    }
  };

  const handleOpenCreateModal = () => {
    setFormData({
      patient_id: "",
      exam: "",
      diagnosis: "",
      conclusion: "",
    });
    setShowCreateModal(true);
  };

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

    if (!formData.patient_id) {
      toast.error("Selecione um paciente");
      return;
    }

    try {
      await reportService.create({
        patient_id: formData.patient_id,
        exam: formData.exam,
        diagnosis: formData.diagnosis,
        conclusion: formData.conclusion,
      });

      toast.success("Relatório criado com sucesso!");
      setShowCreateModal(false);
      loadReports();
    } catch (error) {
      console.error("Erro ao criar relatório:", error);
      toast.error("Erro ao criar relatório");
    }
  };

  const loadReports = async () => {
    setLoading(true);
    try {
      const data = await reportService.list();
      console.log("✅ Relatórios carregados:", data);
      setReports(Array.isArray(data) ? data : []);
      if (Array.isArray(data) && data.length === 0) {
        console.warn("⚠️ Nenhum relatório encontrado na API");
      }
    } catch (error) {
      console.error("❌ Erro ao carregar relatórios:", error);
      toast.error("Erro ao carregar relatórios");
      setReports([]);
    } finally {
      setLoading(false);
    }
  };

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

  const handleClear = () => {
    setSearchTerm("");
    setTypeFilter("Todos");
    setPeriodFilter("Todos");
    loadReports();
  };

  const formatDate = (dateString: string) => {
    try {
      const date = new Date(dateString);
      return date.toLocaleDateString("pt-BR", {
        day: "2-digit",
        month: "2-digit",
        year: "numeric",
        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">Relatórios</h1>
          <p className="text-gray-600 mt-1">
            Visualize e baixe relatórios do sistema
          </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" />
          Novo Relatório
        </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 relatórios..."
              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">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>Financeiro</option>
              <option>Atendimentos</option>
              <option>Pacientes</option>
              <option>Médicos</option>
            </select>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-sm text-gray-600">Período:</span>
            <select
              value={periodFilter}
              onChange={(e) => setPeriodFilter(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>Hoje</option>
              <option>Esta Semana</option>
              <option>Este Mês</option>
              <option>Este Ano</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">
                Relatório
              </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">
                Criado Em
              </th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">
                Solicitante
              </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={5}
                  className="px-6 py-12 text-center text-gray-500"
                >
                  Carregando relatórios...
                </td>
              </tr>
            ) : reports.length === 0 ? (
              <tr>
                <td
                  colSpan={5}
                  className="px-6 py-12 text-center text-gray-500"
                >
                  Nenhum relatório encontrado
                </td>
              </tr>
            ) : (
              reports.map((report) => (
                <tr
                  key={report.id}
                  className="hover:bg-gray-50 transition-colors"
                >
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-3">
                      <div className="p-2 bg-blue-100 rounded-lg">
                        <FileText className="h-5 w-5 text-blue-600" />
                      </div>
                      <div>
                        <p className="text-sm font-medium text-gray-900">
                          {report.order_number}
                        </p>
                        <p className="text-xs text-gray-500">
                          {report.exam || "Sem exame"}
                        </p>
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <span
                      className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${
                        report.status === "completed"
                          ? "bg-green-100 text-green-800"
                          : report.status === "pending"
                          ? "bg-yellow-100 text-yellow-800"
                          : report.status === "draft"
                          ? "bg-gray-100 text-gray-800"
                          : "bg-red-100 text-red-800"
                      }`}
                    >
                      {report.status === "completed"
                        ? "Concluído"
                        : report.status === "pending"
                        ? "Pendente"
                        : report.status === "draft"
                        ? "Rascunho"
                        : "Cancelado"}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-700">
                    {formatDate(report.created_at)}
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-700">
                    {report.requested_by || "—"}
                  </td>
                  <td className="px-6 py-4">
                    <button
                      title="Baixar"
                      disabled={report.status !== "completed"}
                      className={`flex items-center gap-2 px-3 py-1.5 rounded-lg transition-colors ${
                        report.status === "completed"
                          ? "text-green-600 hover:bg-green-50"
                          : "text-gray-400 cursor-not-allowed"
                      }`}
                    >
                      <Download className="h-4 w-4" />
                      <span className="text-sm font-medium">Baixar</span>
                    </button>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* Modal de Criar Relatório */}
      {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">
                Novo Relatório
              </h2>
            </div>

            <form onSubmit={handleCreateReport} className="p-6 space-y-4">
              <div className="space-y-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">
                    Exame
                  </label>
                  <input
                    type="text"
                    value={formData.exam}
                    onChange={(e) =>
                      setFormData({ ...formData, exam: e.target.value })
                    }
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500"
                    placeholder="Nome do exame realizado"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Diagnóstico
                  </label>
                  <textarea
                    value={formData.diagnosis}
                    onChange={(e) =>
                      setFormData({ ...formData, diagnosis: e.target.value })
                    }
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 h-24"
                    placeholder="Diagnóstico do paciente"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Conclusão
                  </label>
                  <textarea
                    value={formData.conclusion}
                    onChange={(e) =>
                      setFormData({ ...formData, conclusion: e.target.value })
                    }
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 h-24"
                    placeholder="Conclusão e recomendações"
                  />
                </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"
                >
                  Criar Relatório
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
