'use client';

import { useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import { X, Gift, FileText } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useSystemConfig } from '@/hooks/useSystemConfig';

export interface PopupDraft {
  enabled: boolean;
  title: string;
  body: string;
  ctaLabel?: string;
  ctaHref?: string;
  version: string;
  requireAcceptance?: boolean;
}

const STORAGE_KEY_PREFIX = 'dashboard_popup_dismissed:';

function readDismissed(key: string): string | null {
  if (typeof window === 'undefined') return null;
  try {
    return window.localStorage.getItem(STORAGE_KEY_PREFIX + key);
  } catch {
    return null;
  }
}

function writeDismissed(key: string, value: string) {
  if (typeof window === 'undefined') return;
  try {
    window.localStorage.setItem(STORAGE_KEY_PREFIX + key, value);
  } catch {}
}

function parseDraft(raw: unknown): PopupDraft | null {
  if (!raw) return null;
  let s = '';
  if (typeof raw === 'string') s = raw;
  else if (typeof raw === 'object') {
    try {
      s = JSON.stringify(raw);
    } catch {
      return null;
    }
  } else {
    return null;
  }
  if (!s) return null;
  try {
    const obj = JSON.parse(s);
    if (obj && typeof obj === 'object' && typeof obj.title === 'string' && typeof obj.body === 'string') {
      return {
        enabled: Boolean(obj.enabled),
        title: String(obj.title),
        body: String(obj.body),
        ctaLabel: typeof obj.ctaLabel === 'string' ? obj.ctaLabel : undefined,
        ctaHref: typeof obj.ctaHref === 'string' ? obj.ctaHref : undefined,
        version: String(obj.version ?? '1'),
        requireAcceptance: Boolean(obj.requireAcceptance),
      };
    }
  } catch {}
  return null;
}

interface PopupProps {
  draft: PopupDraft;
  storageKey: string;
  icon: React.ReactNode;
  onClose: () => void;
  variant?: 'referral' | 'terms';
}

function DashboardPopup({ draft, storageKey, icon, onClose, variant = 'referral' }: PopupProps) {
  const [accepted, setAccepted] = useState(false);

  const handleDismiss = () => {
    if (draft.requireAcceptance && !accepted) return;
    writeDismissed(storageKey, draft.version);
    onClose();
  };

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"
      role="dialog"
      aria-modal="true"
      aria-labelledby={`${storageKey}-title`}
    >
      <div className="w-full max-w-md rounded-2xl border border-white/10 bg-slate-900 shadow-2xl">
        <div className="flex items-start justify-between gap-3 border-b border-white/10 p-5">
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary-500/15 text-primary-400">
              {icon}
            </div>
            <h2 id={`${storageKey}-title`} className="text-lg font-semibold text-white">
              {draft.title}
            </h2>
          </div>
          {!draft.requireAcceptance && (
            <button
              type="button"
              onClick={handleDismiss}
              className="rounded-lg p-1 text-slate-400 hover:text-white"
              aria-label="Close"
            >
              <X className="h-5 w-5" />
            </button>
          )}
        </div>
        <div className="p-5 space-y-4">
          <p className="text-sm leading-relaxed text-slate-300 whitespace-pre-wrap">
            {draft.body}
          </p>
          {draft.requireAcceptance && (
            <label className="flex items-start gap-2 text-sm text-slate-300">
              <input
                type="checkbox"
                checked={accepted}
                onChange={(e) => setAccepted(e.target.checked)}
                className="mt-1 h-4 w-4 rounded border-white/20 bg-white/5"
              />
              <span>
                I have read and accept these {variant === 'terms' ? 'Terms & Conditions' : 'terms'}.
              </span>
            </label>
          )}
          <div className="flex flex-wrap items-center justify-end gap-2">
            {draft.ctaHref && draft.ctaLabel && (
              <Link
                href={draft.ctaHref}
                className="inline-flex items-center justify-center rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-sm font-medium text-slate-200 hover:bg-white/10"
              >
                {draft.ctaLabel}
              </Link>
            )}
            <Button
              onClick={handleDismiss}
              disabled={draft.requireAcceptance && !accepted}
              className="min-w-[120px]"
            >
              {draft.requireAcceptance ? 'Accept & Continue' : 'Got it'}
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}

export function DashboardPopups() {
  const sysConfig = useSystemConfig();
  const [activeKey, setActiveKey] = useState<'referral' | 'terms' | null>(null);

  const referralDraft = useMemo<PopupDraft | null>(() => parseDraft((sysConfig as any).dashboard_popup_referral), [sysConfig]);
  const termsDraft = useMemo<PopupDraft | null>(() => parseDraft((sysConfig as any).dashboard_popup_terms), [sysConfig]);

  useEffect(() => {
    if (!sysConfig.loaded) return;
    if (referralDraft?.enabled && readDismissed('referral') !== referralDraft.version) {
      setActiveKey('referral');
      return;
    }
    if (termsDraft?.enabled && readDismissed('terms') !== termsDraft.version) {
      setActiveKey('terms');
      return;
    }
    setActiveKey(null);
  }, [sysConfig.loaded, referralDraft, termsDraft]);

  if (!activeKey) return null;

  if (activeKey === 'referral' && referralDraft) {
    return (
      <DashboardPopup
        draft={referralDraft}
        storageKey="referral"
        icon={<Gift className="h-5 w-5" />}
        onClose={() => setActiveKey('terms')}
      />
    );
  }

  if (activeKey === 'terms' && termsDraft) {
    return (
      <DashboardPopup
        draft={termsDraft}
        storageKey="terms"
        icon={<FileText className="h-5 w-5" />}
        variant="terms"
        onClose={() => setActiveKey(null)}
      />
    );
  }

  return null;
}

export default DashboardPopups;
