'use client';

import { useEffect, useState } from 'react';
import { X, CheckCircle2, ScrollText } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { termsOfServiceService, type TermsDocument } from '@/services/terms-of-service.service';

interface TermsPopupProps {
  open: boolean;
  onAccept?: () => void;
  onDecline?: () => void;
}

type DocType = 'TERMS' | 'PRIVACY';

export default function TermsPopup({ open, onAccept, onDecline }: TermsPopupProps) {
  const [activeTab, setActiveTab] = useState<DocType>('TERMS');
  const [loading, setLoading] = useState(false);
  const [declining, setDeclining] = useState(false);
  const [termsDoc, setTermsDoc] = useState<TermsDocument | null>(null);
  const [privacyDoc, setPrivacyDoc] = useState<TermsDocument | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!open) return;
    let cancelled = false;
    (async () => {
      setLoading(true);
      setError(null);
      try {
        const { terms, privacy } = await termsOfServiceService.getBothCurrentPublic();
        if (cancelled) return;
        setTermsDoc(terms ?? null);
        setPrivacyDoc(privacy ?? null);
      } catch (e: any) {
        if (!cancelled) setError(e?.response?.data?.message || e?.message || 'Failed to load terms');
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, [open]);

  const handleAccept = async () => {
    setLoading(true);
    try {
      await onAccept?.();
    } catch (err) {
      console.error('Failed to accept terms:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleDecline = () => {
    setDeclining(true);
    onDecline?.();
    if (typeof window !== 'undefined') {
      window.location.assign('/login?session=declined');
    }
  };

  if (!open) return null;

  const activeDoc = activeTab === 'TERMS' ? termsDoc : privacyDoc;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
      <div className="max-h-[90vh] w-full max-w-2xl overflow-auto rounded-2xl border border-line bg-surface p-6">
        <div className="mb-4 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <ScrollText className="h-5 w-5 text-primary-600" />
            <h2 className="text-xl font-bold text-ink">Terms and Conditions</h2>
          </div>
          <button
            onClick={handleDecline}
            className="rounded-lg p-1 text-ink-faint hover:text-ink"
            aria-label="Close"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        <p className="mb-4 text-sm text-ink-muted">
          Please read and accept our Terms and Conditions and Privacy Policy to continue.
        </p>

        <div className="mb-4 flex border-b border-line">
          <button
            onClick={() => setActiveTab('TERMS')}
            className={`flex-1 pb-2 text-sm font-medium transition-colors ${
              activeTab === 'TERMS'
                ? 'border-b-2 border-primary-600 text-primary-600'
                : 'text-ink-faint hover:text-ink'
            }`}
          >
            Terms and Conditions
            {termsDoc && <span className="ml-1 text-xs opacity-60">v{termsDoc.version}</span>}
          </button>
          <button
            onClick={() => setActiveTab('PRIVACY')}
            className={`flex-1 pb-2 text-sm font-medium transition-colors ${
              activeTab === 'PRIVACY'
                ? 'border-b-2 border-primary-600 text-primary-600'
                : 'text-ink-faint hover:text-ink'
            }`}
          >
            Privacy Policy
            {privacyDoc && <span className="ml-1 text-xs opacity-60">v{privacyDoc.version}</span>}
          </button>
        </div>

        <div className="max-h-[50vh] overflow-y-auto rounded-xl border border-line bg-surface-raised p-4">
          {loading ? (
            <p className="text-xs text-ink-faint">Loading current terms…</p>
          ) : error ? (
            <p className="text-xs text-red-500">{error}</p>
          ) : activeDoc ? (
            <>
              <div className="mb-2 text-xs text-ink-faint">
                <strong>{activeDoc.title}</strong>
                {activeDoc.publishedAt && (
                  <> · Last updated {new Date(activeDoc.publishedAt).toLocaleDateString()}</>
                )}
              </div>
              <pre className="whitespace-pre-wrap text-xs leading-relaxed text-ink-muted">
                {activeDoc.content}
              </pre>
            </>
          ) : (
            <p className="text-xs text-ink-faint">Not available.</p>
          )}
        </div>

        <div className="mt-6 flex justify-end gap-3">
          <Button variant="outline" onClick={handleDecline} loading={declining} className="min-w-[120px]">
            <X className="h-4 w-4" />
            {declining ? 'Declining...' : 'Decline'}
          </Button>
          <Button onClick={handleAccept} loading={loading} className="min-w-[160px]">
            <CheckCircle2 className="h-4 w-4" />
            {loading ? 'Accepting...' : 'I Accept'}
          </Button>
        </div>
      </div>
    </div>
  );
}