'use client';

import Link from 'next/link';
import { useCallback, useEffect, useState } from 'react';
import Swal from 'sweetalert2';
import { RequireRole, useAuth } from '@/lib/auth-context';
import { listDentists, removeDentist } from '@/lib/services/dentists';
import type { Dentist } from '@/lib/types';
import {
  EmptyState,
  ErrorAlert,
  Loading,
  PageHeader,
  Pagination,
} from '@/components/app/ui';
import { extractApiError } from '@/lib/api-client';

export default function DentistasPage() {
  return (
    <RequireRole roles={['admin', 'receptionist', 'dentist']}>
      <DentistsView />
    </RequireRole>
  );
}

const PAGE_SIZE = 10;

function photoUrlForDentist(dentist: Dentist): string | null {
  if (!dentist.photoUrl) return null;
  if (/^https?:\/\//i.test(dentist.photoUrl)) return dentist.photoUrl;
  const apiUrl =
    process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api';
  return `${apiUrl}/dentists/${dentist.id}/photo`;
}

function DentistsView() {
  const { user } = useAuth();
  const canCreate = user?.role === 'admin';
  const canDelete = user?.role === 'admin';

  const [items, setItems] = useState<Dentist[]>([]);
  const [total, setTotal] = useState(0);
  const [totalPages, setTotalPages] = useState(1);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [term, setTerm] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const result = await listDentists({
        page,
        limit: PAGE_SIZE,
        search: term || undefined,
      });
      setItems(result.data);
      setTotal(result.total);
      setTotalPages(Math.max(result.totalPages, 1));
    } catch (err) {
      setError(extractApiError(err));
    } finally {
      setLoading(false);
    }
  }, [page, term]);

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

  function handleSearch(e: React.FormEvent) {
    e.preventDefault();
    setPage(1);
    setTerm(search.trim());
  }

  async function handleRemove(dentist: Dentist) {
    const confirmation = await Swal.fire({
      icon: 'warning',
      title: 'Remover dentista?',
      text: dentist.fullName,
      showCancelButton: true,
      confirmButtonText: 'Remover',
      cancelButtonText: 'Cancelar',
      confirmButtonColor: '#dc3545',
    });
    if (!confirmation.isConfirmed) return;

    try {
      await removeDentist(dentist.id);
      await Swal.fire({
        icon: 'success',
        title: 'Dentista removido',
        timer: 1100,
        showConfirmButton: false,
      });
      await load();
    } catch (err) {
      Swal.fire({ icon: 'error', title: 'Erro', text: extractApiError(err) });
    }
  }

  return (
    <>
      <PageHeader
        title="Dentistas"
        subtitle="Corpo clínico da clínica"
        action={
          canCreate && (
            <Link href="/painel/dentistas/novo" className="btn btn-primary">
              <i className="bi bi-plus-lg me-1" />
              Novo dentista
            </Link>
          )
        }
      />

      <form className="row g-2 mb-3" onSubmit={handleSearch}>
        <div className="col-12 col-md-5">
          <div className="input-group">
            <span className="input-group-text">
              <i className="bi bi-search" />
            </span>
            <input
              className="form-control"
              placeholder="Buscar por nome"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              aria-label="Buscar dentista"
            />
          </div>
        </div>
        <div className="col-auto">
          <button className="btn btn-outline-primary" type="submit">
            Buscar
          </button>
        </div>
      </form>

      {error && <ErrorAlert message={error} onRetry={load} />}

      {loading ? (
        <Loading />
      ) : items.length === 0 ? (
        <EmptyState
          icon="bi-person-badge"
          title="Nenhum dentista encontrado"
          description={
            term
              ? 'Ajuste a busca e tente novamente.'
              : 'Cadastre o primeiro dentista da clínica.'
          }
        />
      ) : (
        <div className="card border-0 shadow-sm">
          <div className="table-responsive">
            <table className="table table-hover align-middle mb-0">
              <thead className="table-light">
                <tr>
                  <th>Foto</th>
                  <th>Nome</th>
                  <th>CRO</th>
                  <th>Especialidades</th>
                  <th>Status</th>
                  <th className="text-end">Ações</th>
                </tr>
              </thead>
              <tbody>
                {items.map((dentist) => (
                  <tr key={dentist.id}>
                    <td>
                      {photoUrlForDentist(dentist) ? (
                        <div
                          className="rounded border"
                          role="img"
                          aria-label={`Foto de ${dentist.fullName}`}
                          style={{
                            width: 52,
                            height: 52,
                            backgroundImage: `url(${JSON.stringify(photoUrlForDentist(dentist))})`,
                            backgroundPosition: 'center',
                            backgroundSize: 'cover',
                          }}
                        />
                      ) : (
                        <div
                          className="d-flex flex-column align-items-center justify-content-center rounded border border-secondary text-secondary"
                          style={{ width: 72, height: 52 }}
                          aria-label={`${dentist.fullName} está sem foto`}
                        >
                          <i className="bi bi-camera-video-off" aria-hidden="true" />
                          <small>Sem Foto</small>
                        </div>
                      )}
                    </td>
                    <td className="fw-semibold">{dentist.fullName}</td>
                    <td>
                      {dentist.cro}-{dentist.croState}
                    </td>
                    <td>
                      {dentist.specialties.length === 0 ? (
                        <span className="text-muted">—</span>
                      ) : (
                        dentist.specialties.map((s) => (
                          <span
                            key={s.id}
                            className="badge text-bg-light border me-1"
                          >
                            {s.name}
                          </span>
                        ))
                      )}
                    </td>
                    <td>
                      {dentist.isActive ? (
                        <span className="badge text-bg-success">Ativo</span>
                      ) : (
                        <span className="badge text-bg-secondary">Inativo</span>
                      )}
                    </td>
                    <td className="text-end table-nowrap">
                      <Link
                        href={`/painel/dentistas/${dentist.id}`}
                        className="btn btn-sm btn-outline-primary"
                      >
                        Abrir
                      </Link>
                      {canDelete && (
                        <button
                          type="button"
                          className="btn btn-sm btn-outline-danger ms-1"
                          aria-label={`Remover ${dentist.fullName}`}
                          onClick={() => handleRemove(dentist)}
                        >
                          <i className="bi bi-trash" aria-hidden="true" />
                        </button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div className="card-body pt-0">
            <Pagination
              page={page}
              totalPages={totalPages}
              total={total}
              onChange={setPage}
            />
          </div>
        </div>
      )}
    </>
  );
}
