import { router } from '@inertiajs/react';
import { CheckIcon, CopyIcon, RefreshCwIcon, SparklesIcon } from 'lucide-react';
import { useState } from 'react';
import { formatDateTime } from '@/components/classrooms/format';
import type {
    MeetingAnomaly,
    MeetingAnomalyType,
    MeetingReport,
} from '@/components/classrooms/types';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import { useClipboard } from '@/hooks/use-clipboard';
import meetings from '@/routes/meetings';

const ANOMALY_LABELS: Record<MeetingAnomalyType, string> = {
    below_threshold: 'Sotto il 75%',
    partial: 'Ore incomplete',
    disconnections: 'Disconnessioni',
    late_join: 'Ingresso in ritardo',
    trainer_absent: 'Docente assente',
};

function anomalyVariant(
    type: MeetingAnomalyType,
): 'destructive' | 'secondary' | 'outline' {
    if (type === 'below_threshold' || type === 'trainer_absent') {
        return 'destructive';
    }

    return type === 'partial' ? 'secondary' : 'outline';
}

export default function MeetingReportCard({
    meetingUuid,
    report,
}: {
    meetingUuid: string;
    report: MeetingReport | null | undefined;
}) {
    const [regenerating, setRegenerating] = useState(false);
    const [copiedText, copy] = useClipboard();
    const copied =
        report !== null && report !== undefined && copiedText === report.note;

    function regenerate() {
        setRegenerating(true);

        router.post(
            meetings.aiReport({ meeting: meetingUuid }).url,
            {},
            {
                preserveScroll: true,
                onFinish: () => setRegenerating(false),
            },
        );
    }

    return (
        <div className="space-y-3 rounded-xl border p-4">
            <div className="flex flex-wrap items-start justify-between gap-3">
                <div className="space-y-1">
                    <h2 className="text-base font-medium">
                        Relazione della lezione
                    </h2>
                    <p className="text-muted-foreground text-sm">
                        {report
                            ? `Generata il ${formatDateTime(report.generated_at)}.`
                            : 'Viene scritta automaticamente al termine della lezione.'}
                    </p>
                </div>

                <div className="flex gap-2">
                    {report && (
                        <Button
                            variant="outline"
                            onClick={() => void copy(report.note)}
                        >
                            {copied ? <CheckIcon /> : <CopyIcon />}
                            {copied ? 'Copiata' : 'Copia'}
                        </Button>
                    )}
                    <Button
                        variant={report ? 'outline' : 'default'}
                        onClick={regenerate}
                        disabled={regenerating}
                    >
                        {regenerating ? (
                            <Spinner />
                        ) : report ? (
                            <RefreshCwIcon />
                        ) : (
                            <SparklesIcon />
                        )}
                        {report ? 'Rigenera' : 'Genera'}
                    </Button>
                </div>
            </div>

            {report ? (
                <>
                    {report.anomalies.length > 0 ? (
                        <ul className="space-y-2">
                            {report.anomalies.map((anomaly, index) => (
                                <AnomalyRow
                                    key={`${anomaly.type}-${anomaly.participant_id ?? 'none'}-${index}`}
                                    anomaly={anomaly}
                                />
                            ))}
                        </ul>
                    ) : (
                        <p className="text-muted-foreground text-sm">
                            Nessuna anomalia rilevata.
                        </p>
                    )}

                    <p className="bg-muted/40 rounded-lg p-3 text-sm">
                        {report.note}
                    </p>
                </>
            ) : (
                <p className="text-muted-foreground text-sm">
                    Nessuna relazione disponibile per questa lezione.
                </p>
            )}
        </div>
    );
}

function AnomalyRow({ anomaly }: { anomaly: MeetingAnomaly }) {
    return (
        <li className="flex flex-wrap items-center gap-2 text-sm">
            <Badge variant={anomalyVariant(anomaly.type)}>
                {ANOMALY_LABELS[anomaly.type]}
            </Badge>
            <span className="text-muted-foreground">{anomaly.detail}</span>
        </li>
    );
}
