'use client';

import { useCallback, useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import Swal from 'sweetalert2';
import { RequireRole, useAuth } from '@/lib/auth-context';
import {
  getDentist,
  getMyDentist,
  updateDentist,
  uploadDentistPhoto,
} from '@/lib/services/dentists';
import type { Dentist } from '@/lib/types';
import DentistForm, {
  DentistFormValues,
} from '@/components/app/DentistForm';
import ScheduleManager from '@/components/app/ScheduleManager';
import {
  BackLink,
  ErrorAlert,
  Loading,
  PageHeader,
} from '@/components/app/ui';
import { extractApiError } from '@/lib/api-client';

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

function DentistaDetail() {
  const params = useParams<{ id: string }>();
  const dentistId = Number(params.id);
  const { user } = useAuth();

  const [dentist, setDentist] = useState<Dentist | null>(null);
  const [ownId, setOwnId] = useState<number | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await getDentist(dentistId);
      setDentist(data);
      if (user?.role === 'dentist') {
        try {
          const mine = await getMyDentist();
          setOwnId(mine.id);
        } catch {
          setOwnId(null);
        }
      }
    } catch (err) {
      setError(extractApiError(err));
    } finally {
      setLoading(false);
    }
  }, [dentistId, user?.role]);

  useEffect(() => {
    if (!Number.isNaN(dentistId)) load();
  }, [dentistId, load]);

  const canManage =
    user?.role === 'admin' ||
    (user?.role === 'dentist' && ownId !== null && ownId === dentistId);

  async function handleSubmit(values: DentistFormValues) {
    setSubmitting(true);
    try {
      const updated = await updateDentist(dentistId, {
        fullName: values.fullName,
        cro: values.cro,
        croState: values.croState,
        bio: values.bio || null,
        isActive: values.isActive,
        specialtyIds: values.specialtyIds,
        // userId só é alterável por admin
        ...(user?.role === 'admin'
          ? { userId: values.userId ? Number(values.userId) : null }
          : {}),
      });
      const result = values.photo?.[0]
        ? await uploadDentistPhoto(dentistId, values.photo[0])
        : updated;
      setDentist(result);
      Swal.fire({
        icon: 'success',
        title: 'Dados atualizados',
        timer: 1200,
        showConfirmButton: false,
      });
    } catch (err) {
      Swal.fire({ icon: 'error', title: 'Erro', text: extractApiError(err) });
    } finally {
      setSubmitting(false);
    }
  }

  if (loading) return <Loading />;
  if (error) return <ErrorAlert message={error} onRetry={load} />;
  if (!dentist) return null;

  return (
    <>
      <BackLink href="/painel/dentistas" label="Voltar para dentistas" />
      <PageHeader
        title={dentist.fullName}
        subtitle={`CRO ${dentist.cro}-${dentist.croState}`}
      />

      {!canManage && (
        <div className="alert alert-secondary" role="note">
          <i className="bi bi-eye me-2" />
          Você está visualizando este perfil em modo somente leitura.
        </div>
      )}

      {canManage ? (
        <DentistForm
          initial={dentist}
          canLinkUser={user?.role === 'admin'}
          submitting={submitting}
          onSubmit={handleSubmit}
        />
      ) : (
        <div className="card border-0 shadow-sm">
          <div className="card-body">
            <p className="mb-2">
              <strong>Especialidades:</strong>{' '}
              {dentist.specialties.length
                ? dentist.specialties.map((s) => s.name).join(', ')
                : '—'}
            </p>
            <p className="mb-0 text-muted">
              {dentist.bio || 'Sem mini-currículo cadastrado.'}
            </p>
          </div>
        </div>
      )}

      <div className="mt-3">
        <ScheduleManager dentistId={dentistId} canManage={canManage} />
      </div>
    </>
  );
}
