'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { ArrowLeft, Share2, Copy, CheckCircle2, AlertCircle } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { getReferralCode } from '@/services/referral/referral.service';

export default function ShareInvitePage() {
  const [data, setData] = useState<Awaited<ReturnType<typeof getReferralCode>> | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const res = await getReferralCode();
        if (!cancelled) setData(res);
      } catch (err: any) {
        if (!cancelled) setError(err?.message || 'Failed to load referral code');
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  const copy = (text: string) => {
    if (typeof navigator !== 'undefined' && navigator.clipboard) {
      navigator.clipboard.writeText(text).then(() => {
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      });
    }
  };

  return (
    <div className="space-y-6">
      <Link href="/dashboard/referral" className="inline-flex items-center gap-1 text-sm text-ink-muted hover:text-ink">
        <ArrowLeft className="h-4 w-4" /> Back to Referral Center
      </Link>
      <div>
        <h1 className="text-2xl font-bold tracking-tight text-ink">Share & Invite</h1>
        <p className="mt-1 text-sm text-ink-muted">Share your referral link and earn commissions</p>
      </div>

      {error && (
        <div className="flex items-center gap-2 rounded-xl border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-600 dark:text-red-300">
          <AlertCircle className="h-4 w-4" /> {error}
        </div>
      )}

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Share2 className="h-4 w-4" /> Your Referral Code
          </CardTitle>
          <CardDescription className="mt-1">Share this code with friends to earn commissions</CardDescription>
        </CardHeader>
        <CardContent>
          {loading ? (
            <p className="text-sm text-ink-muted">Loading…</p>
          ) : data ? (
            <div className="space-y-3">
              <div>
                <p className="text-xs uppercase tracking-wide text-ink-muted">Referral code</p>
                <div className="mt-1 flex items-center gap-2">
                  <code className="flex-1 truncate rounded-lg border border-line bg-surface-raised px-3 py-2 text-base font-mono font-semibold text-ink">{data.code}</code>
                  <button
                    onClick={() => copy(data.code)}
                    className="inline-flex items-center gap-1 rounded-lg border border-line px-3 py-1.5 text-xs text-ink-muted hover:bg-surface-raised"
                  >
                    {copied ? <CheckCircle2 className="h-3 w-3" /> : <Copy className="h-3 w-3" />}
                    {copied ? 'Copied' : 'Copy'}
                  </button>
                </div>
              </div>
            </div>
          ) : (
            <p className="text-sm text-ink-faint">No referral code yet.</p>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
