import { Button } from '@/Components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from '@/Components/ui/dialog';
import dayjs from 'dayjs';

type DrugLine = {
    id?: number;
    quantity?: number | string;
    drug?: { name?: string; package_unit?: string } | null;
};

type ReminderInfo = {
    user?: { name?: string; surname?: string } | null;
    message?: string | null;
    next_run_at?: string | null;
    last_sent_at?: string | null;
    remindable_type?: string | null;
    remindable?:
        | (DrugLine & { condition_as_text?: string; message?: string })
        | null;
    batch_prescriptions?: DrugLine[];
    notification_data?: { time?: string; alert_id?: number } | null;
};

type ReminderInfoDialogProps = {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    reminder: ReminderInfo | null;
};

export default function ReminderInfoDialog({
    open,
    onOpenChange,
    reminder,
}: ReminderInfoDialogProps) {
    const batchPrescriptions = reminder?.batch_prescriptions || [];
    const remindable = reminder?.remindable;

    const userLabel = reminder?.user
        ? `${reminder.user.name ?? ''} ${reminder.user.surname ?? ''}`.trim()
        : '';

    const nextRun = reminder?.next_run_at
        ? dayjs(reminder.next_run_at).format('DD.MM.YYYY - HH:mm')
        : '';

    const lastSent = reminder?.last_sent_at
        ? dayjs(reminder.last_sent_at).format('DD.MM.YYYY - HH:mm')
        : '';

    const administrationTimeRaw = reminder?.notification_data?.time || null;
    const administrationTime = administrationTimeRaw
        ? dayjs(administrationTimeRaw).format('DD.MM.YYYY - HH:mm')
        : '';

    const isBatch =
        Array.isArray(batchPrescriptions) && batchPrescriptions.length > 0;
    const isDrugPrescription =
        reminder?.remindable_type === 'App\\Models\\DrugPrescription';
    const isAlert = reminder?.remindable_type === 'App\\Models\\Alert';

    const title = isBatch
        ? 'Dettagli promemoria farmaci'
        : isDrugPrescription
          ? 'Dettagli promemoria farmaco'
          : isAlert
            ? 'Dettagli promemoria alert'
            : 'Dettagli promemoria';

    const renderDrugLine = (p: DrugLine) => {
        const qty = p?.quantity ?? '';
        const unit = p?.drug?.package_unit ?? '';
        const drugName = p?.drug?.name ?? 'Farmaco';
        return `${qty} ${unit} di ${drugName}`.replace(/\s+/g, ' ').trim();
    };

    const singleDrugLine = () => {
        if (!remindable) return null;
        const qty = remindable?.quantity ?? '';
        const unit = remindable?.drug?.package_unit ?? '';
        const drugName = remindable?.drug?.name ?? 'Farmaco';
        return `${qty} ${unit} di ${drugName}`.replace(/\s+/g, ' ').trim();
    };

    const alertLine = () => {
        if (remindable?.condition_as_text) return remindable.condition_as_text;
        if (remindable?.message) return remindable.message;
        if (reminder?.notification_data?.alert_id)
            return `Alert #${reminder.notification_data.alert_id}`;
        return null;
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-w-2xl">
                <DialogHeader>
                    <DialogTitle>{title}</DialogTitle>
                </DialogHeader>

                {!reminder ? null : (
                    <div className="space-y-4">
                        <div className="rounded-md border bg-white p-4">
                            <div className="text-sm text-gray-600">Utente</div>
                            <div className="mt-1 text-base font-medium text-gray-900">
                                {userLabel || '—'}
                            </div>

                            <div className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-3">
                                <div>
                                    <div className="text-sm text-gray-600">
                                        Orario somministrazione
                                    </div>
                                    <div className="mt-1 text-sm text-gray-900">
                                        {administrationTime || '—'}
                                    </div>
                                </div>
                                <div>
                                    <div className="text-sm text-gray-600">
                                        Prossima esecuzione
                                    </div>
                                    <div className="mt-1 text-sm text-gray-900">
                                        {nextRun || '—'}
                                    </div>
                                </div>
                                <div>
                                    <div className="text-sm text-gray-600">
                                        Ultimo invio
                                    </div>
                                    <div className="mt-1 text-sm text-gray-900">
                                        {lastSent || '—'}
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="rounded-md border bg-white p-4">
                            <div className="text-sm text-gray-600">
                                Messaggio
                            </div>
                            <div className="mt-1 text-sm text-gray-900">
                                {reminder.message || '—'}
                            </div>
                        </div>

                        {isBatch ? (
                            <div className="rounded-md border bg-white p-4">
                                <div className="text-sm text-gray-600">
                                    Farmaci previsti
                                </div>
                                <ul className="mt-2 list-disc space-y-1 pl-5 text-sm text-gray-900">
                                    {batchPrescriptions.map((p: DrugLine) => (
                                        <li key={p?.id}>{renderDrugLine(p)}</li>
                                    ))}
                                </ul>
                            </div>
                        ) : isDrugPrescription ? (
                            <div className="rounded-md border bg-white p-4">
                                <div className="text-sm text-gray-600">
                                    Farmaco previsto
                                </div>
                                <div className="mt-2 text-sm text-gray-900">
                                    {singleDrugLine() || '—'}
                                </div>
                            </div>
                        ) : isAlert ? (
                            <div className="rounded-md border bg-white p-4">
                                <div className="text-sm text-gray-600">
                                    Alert associato
                                </div>
                                <div className="mt-2 text-sm text-gray-900">
                                    {alertLine() || '—'}
                                </div>
                            </div>
                        ) : null}

                        <div className="flex justify-end">
                            <Button
                                variant="secondary"
                                onClick={() => onOpenChange(false)}
                            >
                                Chiudi
                            </Button>
                        </div>
                    </div>
                )}
            </DialogContent>
        </Dialog>
    );
}
