import React, { useCallback, useMemo, useRef, useState } from 'react';
import { AlertCircle, AlertTriangle, Info, Trash2 } from 'lucide-react';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogMedia,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { cn } from '@/lib/utils';
import { useLanguage } from './LanguageContext';
import { MessageDialogContext } from './message-dialog-context';

const DIALOG_TONES = {
  info: {
    icon: Info,
    mediaClassName: 'bg-slate-100 text-slate-700',
    actionVariant: 'default',
  },
  warning: {
    icon: AlertTriangle,
    mediaClassName: 'bg-amber-100 text-amber-700',
    actionVariant: 'default',
  },
  danger: {
    icon: Trash2,
    mediaClassName: 'bg-rose-100 text-rose-700',
    actionVariant: 'destructive',
  },
  error: {
    icon: AlertCircle,
    mediaClassName: 'bg-rose-100 text-rose-700',
    actionVariant: 'destructive',
  },
};

function normalizeRequest(request, t) {
  const options = typeof request === 'string' ? { message: request } : request;
  const type = options?.type || 'alert';

  return {
    type,
    tone: options?.tone || (type === 'confirm' ? 'warning' : 'info'),
    title: options?.title || (type === 'confirm' ? t('dialogConfirmTitle') : t('dialogNoticeTitle')),
    message: options?.message || '',
    details: options?.details || '',
    detailsItems: Array.isArray(options?.detailsItems) ? options.detailsItems : [],
    confirmLabel: options?.confirmLabel || (type === 'confirm' ? t('dialogConfirmAction') : t('dialogOk')),
    cancelLabel: options?.cancelLabel || t('cancel'),
  };
}

export function MessageDialogProvider({ children }) {
  const { t } = useLanguage();
  const [dialogConfig, setDialogConfig] = useState(null);
  const resolverRef = useRef(null);

  const closeDialog = useCallback((result) => {
    const resolve = resolverRef.current;
    resolverRef.current = null;
    setDialogConfig(null);
    if (resolve) resolve(result);
  }, []);

  const openDialog = useCallback((request) => {
    const config = normalizeRequest(request, t);
    return new Promise((resolve) => {
      resolverRef.current = resolve;
      setDialogConfig(config);
    });
  }, [t]);

  const value = useMemo(() => ({
    alert: (request) => openDialog({ ...(typeof request === 'string' ? { message: request } : request), type: 'alert' }),
    confirm: (request) => openDialog({ ...(typeof request === 'string' ? { message: request } : request), type: 'confirm' }),
  }), [openDialog]);

  const tone = DIALOG_TONES[dialogConfig?.tone] || DIALOG_TONES.info;
  const ToneIcon = tone.icon;
  const isAlertDialog = dialogConfig?.type === 'alert';
  const hasDetailsItems = Boolean(dialogConfig?.detailsItems?.length);

  return (
    <MessageDialogContext.Provider value={value}>
      {children}
      <AlertDialog open={Boolean(dialogConfig)} onOpenChange={(open) => { if (!open) closeDialog(false); }}>
        <AlertDialogContent className={cn('sm:max-w-xl', isAlertDialog && 'sm:max-w-2xl')}>
          {dialogConfig ? (
            isAlertDialog ? (
              <div className="flex flex-col items-center text-center gap-4">
                <AlertDialogMedia className={cn(tone.mediaClassName, 'mb-0')}>
                  <ToneIcon />
                </AlertDialogMedia>
                <div className="space-y-2">
                  <AlertDialogTitle className="text-center">
                    {dialogConfig.title}
                  </AlertDialogTitle>
                  <AlertDialogDescription className="whitespace-pre-line text-slate-600 text-center max-w-xl mx-auto">
                    {dialogConfig.message}
                  </AlertDialogDescription>
                </div>
                {hasDetailsItems ? (
                  <div className="w-full max-w-xl mx-auto rounded-2xl border bg-slate-50 p-3 sm:p-4">
                    <div className="grid gap-2">
                      {dialogConfig.detailsItems.map((item, index) => (
                        <div key={`${item.label}-${index}`} className="flex items-center justify-between gap-4 rounded-xl bg-white border px-4 py-3 text-left shadow-sm">
                          <span className="text-sm font-medium text-slate-600">{item.label}</span>
                          <span className="inline-flex min-w-10 items-center justify-center rounded-full bg-slate-900 px-3 py-1 text-sm font-bold text-white">{item.value}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                ) : dialogConfig.details ? (
                  <div className="mt-2 w-full max-w-lg mx-auto rounded-2xl border bg-slate-50 px-4 py-3 text-left text-sm whitespace-pre-line text-slate-700">
                    {dialogConfig.details}
                  </div>
                ) : null}
              </div>
            ) : (
              <AlertDialogHeader>
                <AlertDialogMedia className={tone.mediaClassName}>
                  <ToneIcon />
                </AlertDialogMedia>
                <AlertDialogTitle>{dialogConfig.title}</AlertDialogTitle>
                <AlertDialogDescription className="whitespace-pre-line text-slate-600">
                  {dialogConfig.message}
                </AlertDialogDescription>
                {dialogConfig.details ? (
                  <div className="mt-2 w-full rounded-md border bg-slate-50 px-4 py-3 text-left text-sm whitespace-pre-line text-slate-700">
                    {dialogConfig.details}
                  </div>
                ) : null}
              </AlertDialogHeader>
            )
          ) : null}
          <AlertDialogFooter className={cn(isAlertDialog && 'sm:justify-center')}>
            {dialogConfig?.type === 'confirm' ? (
              <AlertDialogCancel onClick={() => closeDialog(false)}>
                {dialogConfig.cancelLabel}
              </AlertDialogCancel>
            ) : null}
            <AlertDialogAction
              variant={tone.actionVariant}
              onClick={() => closeDialog(true)}
            >
              {dialogConfig?.confirmLabel}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </MessageDialogContext.Provider>
  );
}
