import { Gift, Share2 } from 'lucide-react';
import { toast } from 'sonner';

import { useState } from 'react';

import { Head } from '@inertiajs/react';

import EditorialPageHeader from '@/Components/layout/EditorialPageHeader';
import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/Components/ui/card';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { copyToClipboard } from '@/lib/clipboard';
import { couldnt } from '@/lib/messages';

interface ReferralProps {
  referral_url: string;
  referral_count: number;
  /**
   * CAMPAIGN-008 / Pack 3.1 shared prop contract:
   * Human-readable reward copy rendered on the referral card.
   * Example: "1 free month for you + 30% off for your friend"
   * Pack 3.1 reads this prop to render the ReferralCtaCard on the Dashboard.
   * Defaults to a sensible fallback if billing is disabled.
   */
  reward_copy: string;
}

export default function Referral({ referral_url, referral_count, reward_copy }: ReferralProps) {
  const [copied, setCopied] = useState(false);

  // R3UXA-013: use hardened clipboard wrapper — silently swallowing failures
  // meant the button never flipped to "Copied!" and the user got no feedback.
  const copyLink = async () => {
    const ok = await copyToClipboard(referral_url);
    if (ok) {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } else {
      toast.error(couldnt('copy', 'link'));
    }
  };

  const shareNative = async () => {
    if (typeof navigator !== 'undefined' && navigator.share) {
      try {
        await navigator.share({
          title: 'Try RankWizAI free',
          text: 'I use RankWizAI to find traffic opportunities with my Google Search Console data. You can try it free:',
          url: referral_url,
        });
      } catch {
        // User cancelled or API unavailable — fall back to copy
        await copyLink();
      }
    } else {
      await copyLink();
    }
  };

  return (
    <DashboardLayout>
      <Head title="Referral" />
      <EditorialPageHeader
        title="Refer a Friend"
        subtitle="Share RankWizAI and earn rewards when friends upgrade."
      />
      <div className="container py-8">
        <div className="space-y-6 max-w-2xl">
          {/* Reward explanation */}
          <Card className="border-primary/20 bg-primary/5">
            <CardHeader className="pb-3">
              <div className="flex items-center gap-2">
                <Gift className="size-5 text-primary" aria-hidden="true" />
                <CardTitle className="text-base">How referral rewards work</CardTitle>
              </div>
            </CardHeader>
            <CardContent>
              <p className="text-sm text-foreground font-medium">{reward_copy}</p>
              <p className="mt-2 text-xs text-muted-foreground">
                Reward is applied automatically when your friend subscribes to a paid plan.
                No action needed on your end.
              </p>
            </CardContent>
          </Card>

          {/* Referral link */}
          <Card>
            <CardHeader>
              <CardTitle>Your Referral Link</CardTitle>
              <CardDescription>
                Share this link with colleagues, readers, or clients. When someone signs up using
                your link, they get the referral discount automatically.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="referral-url">Referral URL</Label>
                <div className="flex gap-2">
                  <Input
                    id="referral-url"
                    value={referral_url}
                    readOnly
                    className="font-data text-sm"
                    aria-label="Your referral URL"
                  />
                  <Button
                    variant={copied ? 'default' : 'outline'}
                    onClick={copyLink}
                    className="shrink-0"
                    aria-label="Copy referral link"
                  >
                    {copied ? 'Copied!' : 'Copy'}
                  </Button>
                </div>
              </div>
              <Button
                variant="outline"
                onClick={shareNative}
                className="w-full gap-2"
              >
                <Share2 className="size-4" aria-hidden="true" />
                Share link
              </Button>
            </CardContent>
          </Card>

          {/* Stats */}
          <Card>
            <CardHeader>
              <CardTitle>Your Referrals</CardTitle>
              <CardDescription>
                Track how many people have signed up using your referral link.
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex items-center gap-3">
                <span className="text-3xl font-bold text-foreground">{referral_count}</span>
                <Badge variant="secondary">{referral_count === 1 ? 'referral' : 'referrals'}</Badge>
              </div>
              {referral_count === 0 && (
                <p className="mt-3 text-sm text-muted-foreground">
                  Share your link above to start earning rewards.
                </p>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </DashboardLayout>
  );
}
