'use client';

import Link from 'next/link';
import { useEffect, useState } from 'react';
import { RequireRole } from '@/lib/auth-context';
import { useMyPatient } from '@/lib/use-my-patient';
import {
  ErrorAlert,
  Loading,
  PageHeader,
  formatCpf,
} from '@/components/app/ui';
import { formatDateInZone, formatTimeInZone } from '@/lib/datetime';
import {
  getClinicSettings,
  getMyAppointments,
} from '@/lib/services/appointments';
import {
  ACTIVE_APPOINTMENT_STATUSES,
  APPOINTMENT_STATUS_LABELS,
  type Appointment,
} from '@/lib/types';

const FALLBACK_TIMEZONE = 'America/Sao_Paulo';

export default function PortalPage() {
  return (
    <RequireRole roles={['patient']}>
      <PortalHome />
    </RequireRole>
  );
}

function PortalHome() {
  const { patient, loading, error, reload } = useMyPatient();
  const [timezone, setTimezone] = useState(FALLBACK_TIMEZONE);
  const [upcoming, setUpcoming] = useState<Appointment[]>([]);

  useEffect(() => {
    let active = true;
    (async () => {
      try {
        const [settings, page] = await Promise.all([
          getClinicSettings(),
          getMyAppointments(),
        ]);
        if (!active) return;
        if (typeof settings.timezone === 'string') {
          setTimezone(settings.timezone);
        }
        const now = Date.now();
        setUpcoming(
          page.data
            .filter(
              (a) =>
                ACTIVE_APPOINTMENT_STATUSES.includes(a.status) &&
                new Date(a.startAt).getTime() >= now,
            )
            .sort(
              (a, b) =>
                new Date(a.startAt).getTime() - new Date(b.startAt).getTime(),
            ),
        );
      } catch {
        /* silencioso: card mostra estado vazio */
      }
    })();
    return () => {
      active = false;
    };
  }, []);

  if (loading) return <Loading label="Carregando seu portal…" />;
  if (error) return <ErrorAlert message={error} onRetry={reload} />;
  if (!patient) return null;

  return (
    <>
      <PageHeader
        title={`Bem-vindo(a), ${patient.fullName.split(' ')[0]}`}
        subtitle="Seu portal do paciente"
      />

      <div className="row g-3">
        <div className="col-12 col-lg-7">
          <div className="card border-0 shadow-sm h-100">
            <div className="card-body">
              <h2 className="h5 fw-bold mb-3">
                <i className="bi bi-person-vcard me-2 text-primary" />
                Meus dados
              </h2>
              <dl className="row mb-0">
                <dt className="col-sm-4 text-muted fw-normal">Nome</dt>
                <dd className="col-sm-8">{patient.fullName}</dd>
                <dt className="col-sm-4 text-muted fw-normal">CPF</dt>
                <dd className="col-sm-8">{formatCpf(patient.cpf)}</dd>
                <dt className="col-sm-4 text-muted fw-normal">E-mail</dt>
                <dd className="col-sm-8">{patient.email || '—'}</dd>
                <dt className="col-sm-4 text-muted fw-normal">Telefone</dt>
                <dd className="col-sm-8">{patient.phone || '—'}</dd>
              </dl>
              <Link
                href="/portal/meus-dados"
                className="btn btn-sm btn-outline-primary mt-3"
              >
                Ver detalhes
              </Link>
            </div>
          </div>
        </div>

        <div className="col-12 col-lg-5">
          <div className="card border-0 shadow-sm h-100">
            <div className="card-body">
              <h2 className="h5 fw-bold mb-3">
                <i className="bi bi-calendar3 me-2 text-primary" />
                Próximas consultas
              </h2>
              {upcoming.length === 0 ? (
                <>
                  <p className="text-muted mb-2">
                    Você ainda não tem consultas agendadas.
                  </p>
                  <Link href="/agendar" className="btn btn-sm btn-primary">
                    <i className="bi bi-plus-lg me-1" />
                    Agendar consulta
                  </Link>
                </>
              ) : (
                <>
                  <ul className="list-unstyled mb-2">
                    {upcoming.slice(0, 3).map((appointment) => (
                      <li
                        key={appointment.id}
                        className="d-flex justify-content-between border-bottom py-2"
                      >
                        <span>
                          <i className="bi bi-clock me-1 text-muted" />
                          {formatDateInZone(appointment.startAt, timezone)} às{' '}
                          {formatTimeInZone(appointment.startAt, timezone)}
                        </span>
                        <span className="badge text-bg-light border">
                          {APPOINTMENT_STATUS_LABELS[appointment.status]}
                        </span>
                      </li>
                    ))}
                  </ul>
                  <Link
                    href="/portal/consultas"
                    className="btn btn-sm btn-outline-primary"
                  >
                    Ver todas
                  </Link>
                </>
              )}
            </div>
          </div>
        </div>

        <div className="col-12">
          <div className="row g-3">
            <div className="col-6 col-md-4">
              <Link
                href="/portal/consultas"
                className="card border-0 shadow-sm df-card-hover h-100 text-decoration-none"
              >
                <div className="card-body text-center">
                  <i className="bi bi-calendar-check fs-2 text-primary" />
                  <div className="fw-semibold mt-2">Minhas consultas</div>
                  <small className="text-muted">Agende, remarque ou cancele</small>
                </div>
              </Link>
            </div>
            <div className="col-6 col-md-4">
              <Link
                href="/portal/consentimentos"
                className="card border-0 shadow-sm df-card-hover h-100 text-decoration-none"
              >
                <div className="card-body text-center">
                  <i className="bi bi-shield-check fs-2 text-success" />
                  <div className="fw-semibold mt-2">Consentimentos</div>
                  <small className="text-muted">Gerencie seus termos (LGPD)</small>
                </div>
              </Link>
            </div>
            <div className="col-6 col-md-4">
              <Link
                href="/portal/documentos"
                className="card border-0 shadow-sm df-card-hover h-100 text-decoration-none"
              >
                <div className="card-body text-center">
                  <i className="bi bi-folder2-open fs-2 text-primary" />
                  <div className="fw-semibold mt-2">Meus documentos</div>
                  <small className="text-muted">Exames e termos anexados</small>
                </div>
              </Link>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
