import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuth } from "@/hooks/useAuth";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Gift, Copy, CheckCircle2, Users, PoundSterling, Share2, Clock } from "lucide-react";
import { toast } from "sonner";

const csrfToken = () =>
  (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? '';

const REWARD_PERCENT = 15; // 15% of course price credited after completion

const generateCode = (userId: string) => {
  const short = userId.replace(/-/g, "").slice(0, 6).toUpperCase();
  return `REF-${short}-${Date.now().toString(36).toUpperCase().slice(-4)}`;
};

const ReferralModule = () => {
  const { user } = useAuth();
  const queryClient = useQueryClient();
  const [copied, setCopied] = useState(false);

  const { data: referrals, isLoading } = useQuery({
    queryKey: ["delegate-referrals", user?.id],
    enabled: !!user?.id,
    queryFn: async () => {
      const res = await fetch(`/api/delegate/referrals?user_id=${user!.id}`);
      if (!res.ok) throw new Error("Failed to load referrals");
      const data = await res.json();
      return data || [];
    },
  });

  // Pull credit notes the current user can spend; we surface only those whose
  // reason is the referral-reward marker, so the displayed balance reflects
  // unspent referral credit specifically (refund credits don't get counted).
  const { data: creditNotes } = useQuery({
    queryKey: ["referral-credit-notes", user?.id],
    enabled: !!user?.id,
    queryFn: async () => {
      const params = new URLSearchParams();
      if ((user as any)?.company_id) params.set('company_id', (user as any).company_id);
      const res = await fetch(`/api/credit-notes/applicable?${params.toString()}`);
      if (!res.ok) return [];
      return await res.json();
    },
  });

  const referralCreditCents = (creditNotes || [])
    .filter((n: any) => typeof n.reason === 'string' && n.reason.startsWith('Referral reward'))
    .reduce((s: number, n: any) => s + (n.balance_cents || 0), 0);

  const createCodeMutation = useMutation({
    mutationFn: async () => {
      const code = generateCode(user!.id);
      const res = await fetch('/api/delegate/referrals', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken() },
        body: JSON.stringify({
          referrer_user_id: user!.id,
          referral_code: code,
          reward_credit_cents: 0, // calculated at conversion time based on course price
        }),
      });
      if (!res.ok) throw new Error("Failed to create referral");
      return code;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["delegate-referrals"] });
      toast.success("Referral link created!");
    },
    onError: () => toast.error("Failed to create referral link"),
  });

  // Find an active/unused referral code to share
  const activeCode = referrals?.find((r: any) => r.status === "pending" && !r.referred_email)?.referral_code;
  const referralLink = activeCode
    ? `${window.location.origin}/courses?ref=${activeCode}`
    : null;

  const completed = referrals?.filter((r: any) => r.status === "converted" && r.reward_applied) || [];
  const awaitingCompletion = referrals?.filter((r: any) => r.status === "converted" && !r.reward_applied) || [];
  const pending = referrals?.filter((r: any) => r.status === "pending" && r.referred_email) || [];
  const totalEarned = completed.reduce((sum: number, r: any) => sum + (r.reward_credit_cents || 0), 0);

  const handleCopy = async () => {
    if (!referralLink) return;
    try {
      await navigator.clipboard.writeText(referralLink);
      setCopied(true);
      toast.success("Link copied to clipboard!");
      setTimeout(() => setCopied(false), 2000);
    } catch {
      toast.error("Failed to copy link");
    }
  };

  const handleShare = async () => {
    if (!referralLink) return;
    if (navigator.share) {
      try {
        await navigator.share({
          title: "Join me on Locktel Academy",
          text: "Use my referral link to book training courses and we both earn credit!",
          url: referralLink,
        });
      } catch {}
    } else {
      handleCopy();
    }
  };

  if (isLoading) return null;

  return (
    <div className="space-y-3">
      {/* Main referral card */}
      <Card className="bg-gradient-to-br from-primary/5 to-primary/10 border-primary/20">
        <CardContent className="py-5">
          <div className="flex items-start gap-3 mb-4">
            <div className="w-10 h-10 rounded-lg bg-primary/15 flex items-center justify-center shrink-0">
              <Gift className="w-5 h-5 text-primary" />
            </div>
            <div>
              <h3 className="font-semibold text-foreground">Refer a Colleague</h3>
              <p className="text-xs text-muted-foreground mt-0.5">
                They get <span className="font-semibold text-primary">{REWARD_PERCENT}% off</span> their booking.
                You earn <span className="font-semibold text-primary">{REWARD_PERCENT}% credit</span> when they complete the course.
              </p>
            </div>
          </div>

          {referralLink ? (
            <div className="space-y-3">
              <div className="flex items-center gap-2 bg-background rounded-lg border border-border p-2.5">
                <code className="text-xs text-muted-foreground flex-1 truncate">{referralLink}</code>
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-7 shrink-0"
                  onClick={handleCopy}
                >
                  {copied ? <CheckCircle2 className="w-3.5 h-3.5 text-green-600" /> : <Copy className="w-3.5 h-3.5" />}
                </Button>
              </div>
              <div className="flex gap-2">
                <Button size="sm" className="flex-1 h-8 text-xs" onClick={handleCopy}>
                  <Copy className="w-3 h-3 mr-1" /> Copy Link
                </Button>
                <Button size="sm" variant="outline" className="flex-1 h-8 text-xs" onClick={handleShare}>
                  <Share2 className="w-3 h-3 mr-1" /> Share
                </Button>
              </div>
            </div>
          ) : (
            <Button
              size="sm"
              className="w-full h-9"
              onClick={() => createCodeMutation.mutate()}
              disabled={createCodeMutation.isPending}
            >
              <Gift className="w-4 h-4 mr-1.5" />
              {createCodeMutation.isPending ? "Creating..." : "Get My Referral Link"}
            </Button>
          )}
        </CardContent>
      </Card>

      {/* How it works */}
      <Card>
        <CardContent className="py-3">
          <p className="text-xs font-medium text-foreground mb-2">How it works</p>
          <ol className="text-[11px] text-muted-foreground space-y-1 list-decimal list-inside">
            <li>Share your unique link with a colleague</li>
            <li>They book through your link and get {REWARD_PERCENT}% off their order</li>
            <li>Once their course is marked complete, you earn {REWARD_PERCENT}% of what they paid as credit</li>
            <li>Your credit shows up automatically at checkout next time you book — apply it to reduce the amount due</li>
          </ol>
        </CardContent>
      </Card>

      {/* Spendable balance — pulled from credit_notes issued by the referral
          system. Always rendered if there's any unspent balance; this is what
          the user actually has to spend at checkout. */}
      {referralCreditCents > 0 && (
        <Card className="border-primary/30 bg-primary/5">
          <CardContent className="py-3 px-3 flex items-center gap-3">
            <div className="w-9 h-9 rounded-lg bg-primary/15 flex items-center justify-center shrink-0">
              <PoundSterling className="w-4 h-4 text-primary" />
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-lg font-bold text-foreground leading-tight">
                £{(referralCreditCents / 100).toFixed(2)}
              </p>
              <p className="text-[10px] text-muted-foreground">
                Spendable referral credit — applied at checkout
              </p>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Stats row */}
      {(completed.length > 0 || awaitingCompletion.length > 0 || pending.length > 0) && (
        <div className="grid grid-cols-3 gap-2">
          <Card>
            <CardContent className="py-3 px-3 text-center">
              <PoundSterling className="w-4 h-4 text-primary mx-auto mb-1" />
              <p className="text-lg font-bold text-foreground">£{(totalEarned / 100).toFixed(0)}</p>
              <p className="text-[10px] text-muted-foreground">Earned (lifetime)</p>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="py-3 px-3 text-center">
              <Clock className="w-4 h-4 text-amber-500 mx-auto mb-1" />
              <p className="text-lg font-bold text-foreground">{awaitingCompletion.length}</p>
              <p className="text-[10px] text-muted-foreground">Awaiting Cert</p>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="py-3 px-3 text-center">
              <Users className="w-4 h-4 text-muted-foreground mx-auto mb-1" />
              <p className="text-lg font-bold text-foreground">{pending.length}</p>
              <p className="text-[10px] text-muted-foreground">Pending</p>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Recent referral activity */}
      {referrals && referrals.filter((r: any) => r.referred_email).length > 0 && (
        <div className="space-y-1.5">
          <p className="text-xs font-medium text-muted-foreground">Recent Referrals</p>
          {referrals.filter((r: any) => r.referred_email).slice(0, 5).map((ref: any) => (
            <div key={ref.id} className="flex items-center justify-between py-1.5 px-2 rounded bg-muted/30">
              <span className="text-xs text-foreground truncate max-w-[180px]">{ref.referred_email}</span>
              <Badge
                variant={ref.status === "converted" && ref.reward_applied ? "default" : "outline"}
                className={`text-[10px] ${
                  ref.status === "converted" && !ref.reward_applied
                    ? "text-amber-600 border-amber-300"
                    : ref.status === "pending"
                    ? "text-muted-foreground"
                    : ""
                }`}
              >
                {ref.status === "converted" && ref.reward_applied
                  ? `+£${((ref.reward_credit_cents || 0) / 100).toFixed(0)}`
                  : ref.status === "converted"
                  ? "Awaiting Cert"
                  : "Pending"}
              </Badge>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default ReferralModule;
