'use client';

import { useCallback, useEffect, useState } from 'react';
import Swal from 'sweetalert2';
import {
  createSchedule,
  listSchedules,
  removeSchedule,
  updateSchedule,
} from '@/lib/services/dentists';
import { DentistSchedule, WEEKDAYS } from '@/lib/types';
import { EmptyState, Loading, formatDate } from '@/components/app/ui';
import { extractApiError } from '@/lib/api-client';

const WEEKDAY_LABELS = new Map<number, string>(
  WEEKDAYS.map((w) => [w.value, w.label]),
);

function toHHMM(value: string): string {
  return value.slice(0, 5);
}

export default function ScheduleManager({
  dentistId,
  canManage,
}: {
  dentistId: number;
  canManage: boolean;
}) {
  const [items, setItems] = useState<DentistSchedule[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      setItems(await listSchedules(dentistId));
    } catch (err) {
      setError(extractApiError(err));
    } finally {
      setLoading(false);
    }
  }, [dentistId]);

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

  async function handleForm(schedule?: DentistSchedule) {
    const weekdayOptions = WEEKDAYS.map(
      (w) =>
        `<option value="${w.value}" ${schedule?.weekday === w.value ? 'selected' : ''}>${w.label}</option>`,
    ).join('');

    const { value } = await Swal.fire({
      title: schedule ? 'Editar horário' : 'Novo horário',
      html: `
        <div class="text-start">
          <label class="form-label">Dia da semana</label>
          <select id="sw-day" class="form-select mb-2">${weekdayOptions}</select>
          <div class="row g-2">
            <div class="col-6">
              <label class="form-label">Início</label>
              <input id="sw-start" type="time" class="form-control" value="${schedule ? toHHMM(schedule.startTime) : '08:00'}">
            </div>
            <div class="col-6">
              <label class="form-label">Fim</label>
              <input id="sw-end" type="time" class="form-control" value="${schedule ? toHHMM(schedule.endTime) : '12:00'}">
            </div>
          </div>
          <label class="form-label mt-2">Duração do slot (min)</label>
          <input id="sw-slot" type="number" min="5" step="5" class="form-control" value="${schedule?.slotMinutes ?? 30}">
        </div>`,
      focusConfirm: false,
      showCancelButton: true,
      confirmButtonText: 'Salvar',
      cancelButtonText: 'Cancelar',
      preConfirm: () => {
        const weekday = Number(
          (document.getElementById('sw-day') as HTMLSelectElement).value,
        );
        const startTime = (
          document.getElementById('sw-start') as HTMLInputElement
        ).value;
        const endTime = (document.getElementById('sw-end') as HTMLInputElement)
          .value;
        const slotMinutes = Number(
          (document.getElementById('sw-slot') as HTMLInputElement).value,
        );
        if (!startTime || !endTime) {
          Swal.showValidationMessage('Informe início e fim');
          return false;
        }
        if (startTime >= endTime) {
          Swal.showValidationMessage('O início deve ser anterior ao fim');
          return false;
        }
        return { weekday, startTime, endTime, slotMinutes };
      },
    });

    if (!value) return;

    try {
      if (schedule) {
        await updateSchedule(dentistId, schedule.id, value);
      } else {
        await createSchedule(dentistId, value);
      }
      load();
    } catch (err) {
      Swal.fire({ icon: 'error', title: 'Erro', text: extractApiError(err) });
    }
  }

  async function handleRemove(schedule: DentistSchedule) {
    const confirm = await Swal.fire({
      icon: 'warning',
      title: 'Remover horário?',
      showCancelButton: true,
      confirmButtonText: 'Remover',
      cancelButtonText: 'Cancelar',
      confirmButtonColor: '#dc3545',
    });
    if (!confirm.isConfirmed) return;
    try {
      await removeSchedule(dentistId, schedule.id);
      load();
    } catch (err) {
      Swal.fire({ icon: 'error', title: 'Erro', text: extractApiError(err) });
    }
  }

  return (
    <div className="card border-0 shadow-sm">
      <div className="card-header bg-white d-flex justify-content-between align-items-center">
        <span className="fw-semibold">
          <i className="bi bi-clock-history me-2 text-primary" />
          Horários de atendimento
        </span>
        {canManage && (
          <button
            className="btn btn-sm btn-primary"
            onClick={() => handleForm()}
          >
            <i className="bi bi-plus-lg me-1" />
            Novo horário
          </button>
        )}
      </div>

      {loading ? (
        <Loading label="Carregando horários…" />
      ) : error ? (
        <div className="alert alert-danger m-3 mb-0">{error}</div>
      ) : items.length === 0 ? (
        <EmptyState
          icon="bi-clock"
          title="Sem horários definidos"
          description="Defina a grade de atendimento do dentista."
        />
      ) : (
        <div className="table-responsive">
          <table className="table align-middle mb-0">
            <thead className="table-light">
              <tr>
                <th>Dia</th>
                <th>Início</th>
                <th>Fim</th>
                <th>Slot</th>
                <th>Vigência</th>
                <th>Status</th>
                {canManage && <th className="text-end">Ações</th>}
              </tr>
            </thead>
            <tbody>
              {items.map((schedule) => (
                <tr key={schedule.id}>
                  <td className="fw-semibold">
                    {WEEKDAY_LABELS.get(schedule.weekday) ?? schedule.weekday}
                  </td>
                  <td>{toHHMM(schedule.startTime)}</td>
                  <td>{toHHMM(schedule.endTime)}</td>
                  <td>{schedule.slotMinutes} min</td>
                  <td className="text-muted">
                    {schedule.validFrom || schedule.validTo
                      ? `${formatDate(schedule.validFrom)} – ${formatDate(schedule.validTo)}`
                      : 'Sempre'}
                  </td>
                  <td>
                    {schedule.isActive ? (
                      <span className="badge text-bg-success">Ativo</span>
                    ) : (
                      <span className="badge text-bg-secondary">Inativo</span>
                    )}
                  </td>
                  {canManage && (
                    <td className="text-end table-nowrap">
                      <button
                        className="btn btn-sm btn-outline-secondary me-1"
                        onClick={() => handleForm(schedule)}
                        aria-label="Editar horário"
                      >
                        <i className="bi bi-pencil" />
                      </button>
                      <button
                        className="btn btn-sm btn-outline-danger"
                        onClick={() => handleRemove(schedule)}
                        aria-label="Remover horário"
                      >
                        <i className="bi bi-trash" />
                      </button>
                    </td>
                  )}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
