import { useEffect, useState } from 'react';
import { usePrefersReducedMotion } from '@/hooks/use-reduced-motion';

/**
 * "Il registro che si scrive da solo" — l'oggetto su cui poggia tutta
 * l'identità: un foglio presenze vero che si compila riga per riga.
 *
 * Vive qui, e non dentro la landing, perché lo usano due pagine con due
 * comportamenti diversi: la vetrina lo anima una volta sola al caricamento,
 * le pagine di accesso lo mostrano già chiuso, perché lì l'attore è il form e
 * il registro è solo la prova di cosa si sta per entrare a usare. I colori
 * arrivano dai token semantici, quindi il pannello segue il tema dell'utente
 * dentro l'app e resta chiaro sulle pagine pubbliche, che chiare sono.
 */

const ATTENDANCE_ROWS = [
    { name: 'M. Rossi', entry: '09:03' },
    { name: 'A. Bianchi', entry: '09:04' },
    { name: 'L. Verdi', entry: '09:05' },
    { name: 'S. Conti', entry: '09:06' },
];

/** Una tappa per riga, più una finale che chiude l'ultima riga con uscita e durata. */
const SEQUENCE_DELAYS = [150, 700, 1250, 1800, 2700];
const FINAL_STEP = SEQUENCE_DELAYS.length;
const LAST_ROW = ATTENDANCE_ROWS.length - 1;

type Props = {
    /** A `false` il pannello parte già nello stato finale, senza transizioni. */
    animate?: boolean;
};

export function AttendancePanel({ animate = true }: Props) {
    const reducedMotion = usePrefersReducedMotion();
    const [step, setStep] = useState(0);
    const still = reducedMotion || !animate;

    useEffect(() => {
        if (still) {
            return;
        }

        const timers = SEQUENCE_DELAYS.map((delay, index) =>
            setTimeout(() => setStep(index + 1), delay),
        );

        return () => timers.forEach(clearTimeout);
    }, [still]);

    const currentStep = still ? FINAL_STEP : step;
    const closed = currentStep >= FINAL_STEP;

    return (
        <div className="bg-card rounded-marketing -rotate-[1.2deg] border">
            <div className="flex items-baseline justify-between gap-3 border-b px-4 py-3 sm:px-5">
                <p className="text-muted-foreground text-[0.8125rem] font-medium">
                    Aula · Sicurezza sul lavoro — modulo 3
                </p>
                <p className="marketing-data text-muted-foreground text-[0.8125rem]">
                    09:47
                </p>
            </div>

            <table className="w-full table-fixed border-collapse">
                <caption className="sr-only">
                    Registro presenze dell’aula, compilato in automatico
                </caption>
                <thead>
                    <tr className="text-muted-foreground text-left text-[0.75rem] font-medium">
                        <th
                            scope="col"
                            className="w-[42%] px-4 py-2 font-medium sm:px-5"
                        >
                            Partecipante
                        </th>
                        <th
                            scope="col"
                            className="px-1 py-2 text-right font-medium"
                        >
                            Entrata
                        </th>
                        <th
                            scope="col"
                            className="px-1 py-2 text-right font-medium"
                        >
                            Uscita
                        </th>
                        <th
                            scope="col"
                            className="px-4 py-2 text-right font-medium sm:px-5"
                        >
                            Durata
                        </th>
                    </tr>
                </thead>
                <tbody>
                    {ATTENDANCE_ROWS.map((row, index) => {
                        const visible = currentStep >= index + 1;
                        const isLast = index === LAST_ROW;
                        const done = isLast && closed;

                        return (
                            <tr
                                key={row.name}
                                style={{ opacity: visible ? 1 : 0 }}
                                className={`border-border/70 border-t ${
                                    still
                                        ? ''
                                        : 'transition-opacity duration-300 ease-out'
                                }`}
                            >
                                <th
                                    scope="row"
                                    className="text-foreground px-4 py-2.5 text-left text-[0.8125rem] font-medium sm:px-5"
                                >
                                    <span className="flex items-center gap-2">
                                        {done ? (
                                            <CheckStamp />
                                        ) : (
                                            <PresenceDot
                                                pulse={visible && !still}
                                            />
                                        )}
                                        <span className="truncate">
                                            {row.name}
                                        </span>
                                    </span>
                                </th>
                                <td className="marketing-data text-foreground px-1 py-2.5 text-right text-[0.8125rem]">
                                    {visible ? row.entry : ''}
                                </td>
                                <td className="marketing-data text-muted-foreground px-1 py-2.5 text-right text-[0.8125rem]">
                                    {done ? '09:47' : '—'}
                                </td>
                                <td className="marketing-data text-muted-foreground px-4 py-2.5 text-right text-[0.8125rem] sm:px-5">
                                    {done ? '00:41' : '—'}
                                </td>
                            </tr>
                        );
                    })}
                </tbody>
            </table>
        </div>
    );
}

function PresenceDot({ pulse }: { pulse: boolean }) {
    return (
        <span className="relative inline-flex size-2 shrink-0">
            <span className="bg-primary absolute inset-0 rounded-full" />
            {pulse && (
                <span className="marketing-ping-once bg-primary absolute inset-0 rounded-full" />
            )}
            <span className="sr-only">In aula</span>
        </span>
    );
}

function CheckStamp() {
    return (
        <span className="text-primary inline-flex shrink-0">
            <svg viewBox="0 0 16 16" aria-hidden="true" className="size-3.5">
                <circle
                    cx="8"
                    cy="8"
                    r="7"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="1.25"
                />
                <path
                    d="M4.8 8.2 6.9 10.3 11.2 6"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="1.5"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                />
            </svg>
            <span className="sr-only">Presenza chiusa</span>
        </span>
    );
}

export default AttendancePanel;
