import React, { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { availabilityService } from "../../services/index";
import type {
  DoctorException,
  ExceptionKind,
} from "../../services/availability/types";

interface Props {
  doctorId: string;
}

const ExceptionsManager: React.FC<Props> = ({ doctorId }) => {
  const [list, setList] = useState<DoctorException[]>([]);
  const [loading, setLoading] = useState(false);
  const [form, setForm] = useState({
    date: "",
    start_time: "",
    end_time: "",
    kind: "bloqueio" as ExceptionKind,
    reason: "",
  });
  const [saving, setSaving] = useState(false);

  async function load() {
    if (!doctorId) return;
    setLoading(true);
    try {
      const exceptions = await availabilityService.listExceptions({
        doctor_id: doctorId,
      });
      setList(exceptions);
    } catch (error) {
      console.error("Erro ao carregar exceções:", error);
      toast.error("Erro ao carregar exceções");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    void load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [doctorId]);

  async function addException(e: React.FormEvent) {
    e.preventDefault();
    if (!doctorId || !form.date || !form.kind) {
      toast.error("Preencha data e tipo");
      return;
    }
    setSaving(true);
    try {
      await availabilityService.createException({
        doctor_id: doctorId,
        date: form.date,
        start_time: form.start_time || undefined,
        end_time: form.end_time || undefined,
        kind: form.kind,
        reason: form.reason || undefined,
        created_by: doctorId, // Usando doctorId como criador
      });
      toast.success("Exceção criada");
      setForm({
        date: "",
        start_time: "",
        end_time: "",
        kind: "bloqueio",
        reason: "",
      });
      void load();
    } catch (error) {
      console.error("Falha ao criar exceção:", error);
      toast.error("Falha ao criar");
    } finally {
      setSaving(false);
    }
  }

  async function remove(item: DoctorException) {
    if (!item.id) return;
    const ok = confirm("Remover exceção?");
    if (!ok) return;
    try {
      await availabilityService.deleteException(item.id);
      toast.success("Removida");
      void load();
    } catch (error) {
      console.error("Falha ao remover exceção:", error);
      toast.error("Falha ao remover");
    }
  }

  return (
    <div className="bg-white rounded-xl shadow-md p-6 border border-gray-200">
      <h3 className="text-lg font-semibold text-gray-900 mb-4">
        Exceções (Bloqueios/Liberações)
      </h3>
      <form onSubmit={addException} className="mb-6">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-6 gap-4 mb-4">
          <div className="flex flex-col">
            <label className="text-sm font-medium text-gray-700 mb-1">
              Data
            </label>
            <input
              type="date"
              value={form.date}
              onChange={(e) => setForm((f) => ({ ...f, date: e.target.value }))}
              className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-600 focus:border-blue-600/40 transition-colors"
              required
            />
          </div>
          <div className="flex flex-col">
            <label className="text-sm font-medium text-gray-700 mb-1">
              Início{" "}
              <span className="text-gray-400 font-normal">(opcional)</span>
            </label>
            <input
              type="time"
              value={form.start_time}
              onChange={(e) =>
                setForm((f) => ({ ...f, start_time: e.target.value }))
              }
              className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-600 focus:border-blue-600/40 transition-colors"
              placeholder="Dia todo"
            />
          </div>
          <div className="flex flex-col">
            <label className="text-sm font-medium text-gray-700 mb-1">
              Fim <span className="text-gray-400 font-normal">(opcional)</span>
            </label>
            <input
              type="time"
              value={form.end_time}
              onChange={(e) =>
                setForm((f) => ({ ...f, end_time: e.target.value }))
              }
              className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-600 focus:border-blue-600/40 transition-colors"
              placeholder="Dia todo"
            />
          </div>
          <div className="flex flex-col">
            <label className="text-sm font-medium text-gray-700 mb-1">
              Tipo
            </label>
            <select
              value={form.kind}
              onChange={(e) =>
                setForm((f) => ({
                  ...f,
                  kind: e.target.value as ExceptionKind,
                }))
              }
              className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-600 focus:border-blue-600/40 transition-colors"
            >
              <option value="bloqueio">Bloqueio</option>
              <option value="liberacao">Liberação</option>
            </select>
          </div>
          <div className="flex flex-col md:col-span-2">
            <label className="text-sm font-medium text-gray-700 mb-1">
              Motivo{" "}
              <span className="text-gray-400 font-normal">(opcional)</span>
            </label>
            <input
              type="text"
              value={form.reason}
              onChange={(e) =>
                setForm((f) => ({ ...f, reason: e.target.value }))
              }
              className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-600 focus:border-blue-600/40 transition-colors"
              placeholder="Ex.: Férias, Reunião, etc."
            />
          </div>
          <div className="flex flex-col justify-end">
            <button
              type="submit"
              disabled={saving}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
            >
              {saving ? "Salvando..." : "Adicionar"}
            </button>
          </div>
        </div>
      </form>

      {loading ? (
        <div className="flex justify-center py-8">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600" />
        </div>
      ) : list.length === 0 ? (
        <div className="text-center py-8 text-sm text-gray-500">
          Nenhuma exceção cadastrada. Use o formulário acima para
          bloquear/liberar horários.
        </div>
      ) : (
        <div className="overflow-x-auto rounded-lg border border-gray-200">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50 sticky top-0 z-10">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Data
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Horário Início
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Horário Fim
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Tipo
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Motivo
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Ações
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {list.map((item) => (
                <tr
                  key={item.id}
                  className="odd:bg-white even:bg-gray-50 hover:bg-blue-50/40 transition-colors"
                >
                  <td className="px-4 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                    {item.date
                      ? new Date(item.date + "T00:00:00").toLocaleDateString(
                          "pt-BR"
                        )
                      : "—"}
                  </td>
                  <td className="px-4 py-4 whitespace-nowrap text-sm text-gray-900">
                    {item.start_time ? (
                      item.start_time.slice(0, 5)
                    ) : (
                      <span className="text-gray-400">Dia todo</span>
                    )}
                  </td>
                  <td className="px-4 py-4 whitespace-nowrap text-sm text-gray-900">
                    {item.end_time ? (
                      item.end_time.slice(0, 5)
                    ) : (
                      <span className="text-gray-400">Dia todo</span>
                    )}
                  </td>
                  <td className="px-4 py-4 whitespace-nowrap">
                    <span
                      className={`px-3 py-1 rounded-full text-xs font-medium ring-1 ${
                        item.kind === "bloqueio"
                          ? "bg-red-50 text-red-700 ring-red-600/20"
                          : "bg-green-50 text-green-700 ring-green-600/20"
                      }`}
                    >
                      {item.kind === "bloqueio" ? "Bloqueio" : "Liberação"}
                    </span>
                  </td>
                  <td className="px-4 py-4 text-sm text-gray-900">
                    {item.reason || <span className="text-gray-400">—</span>}
                  </td>
                  <td className="px-4 py-4 whitespace-nowrap text-sm font-medium">
                    <button
                      className="inline-flex items-center gap-1 rounded-md px-2.5 py-1.5 text-red-700 bg-red-50 hover:bg-red-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
                      onClick={() => void remove(item)}
                    >
                      Remover
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

export default ExceptionsManager;
