import { useState, useMemo } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useParams, useSearch, Link } from "wouter";
import { useLanguage } from "../contexts/LanguageContext";
import { useCart } from "../contexts/CartContext";
import {
  useGetRequest, useDonateToRequest,
  getListRequestsQueryKey, getListPublishedRequestsQueryKey, getGetRequestQueryKey,
} from "@workspace/api-client-react";
import { useQueryClient } from "@tanstack/react-query";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Gift, Check, Copy, Info, Eye, Clock, Users, Radio } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
import { getNeedImage } from "../lib/needImages";
import { Riyal } from "@/components/Riyal";

const PRESETS = [100, 50, 10];

// POC: receipt/reference numbers are not returned by the API, so we synthesize
// plausible values on the client at the moment the donation succeeds.
function generateReceiptNo(): string {
  let s = "";
  for (let i = 0; i < 15; i++) s += Math.floor(Math.random() * 10);
  return s;
}

function generateReferenceNo(): string {
  if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
    return crypto.randomUUID();
  }
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
    const r = (Math.random() * 16) | 0;
    const v = c === "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

// Subtle EHSAN-style overlapping-circles geometric pattern.
const PATTERN_SVG = encodeURIComponent(
  `<svg xmlns='http://www.w3.org/2000/svg' width='120' height='120' viewBox='0 0 120 120'><g fill='none' stroke='#17a85a' stroke-width='1'><circle cx='0' cy='0' r='60'/><circle cx='120' cy='0' r='60'/><circle cx='0' cy='120' r='60'/><circle cx='120' cy='120' r='60'/><circle cx='60' cy='60' r='60'/></g></svg>`
);
const PATTERN_BG = `url("data:image/svg+xml,${PATTERN_SVG}")`;

// Stable per-case pseudo-random seed so POC stat values don't flicker on re-render.
function hashStr(s: string): number {
  let h = 0;
  for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0;
  return h;
}

const schema = z.object({
  donorName: z.string().min(2),
  donorPhone: z.string().min(10),
  donorEmail: z.string().email().optional().or(z.literal("")),
});

type FormData = z.infer<typeof schema>;

export default function Donate() {
  const { t } = useLanguage();
  const params = useParams<{ id: string }>();
  const search = useSearch();
  const queryClient = useQueryClient();
  const { removeItem: removeFromCart } = useCart();

  const initialAmount = (() => {
    const a = Number(new URLSearchParams(search).get("amount"));
    return Number.isFinite(a) && a > 0 ? String(a) : "";
  })();

  const [step, setStep] = useState<1 | 2>(1);
  const [amount, setAmount] = useState<string>(initialAmount);
  const [amountError, setAmountError] = useState(false);
  const [onBehalf, setOnBehalf] = useState(false);
  const [onBehalfName, setOnBehalfName] = useState("");
  const [donated, setDonated] = useState(false);
  const [donatedAmount, setDonatedAmount] = useState(0);
  const [receiptNo, setReceiptNo] = useState("");
  const [referenceNo, setReferenceNo] = useState("");
  const [copiedField, setCopiedField] = useState<"receipt" | "reference" | null>(null);

  const copyToClipboard = async (value: string, field: "receipt" | "reference") => {
    try {
      if (navigator.clipboard?.writeText) {
        await navigator.clipboard.writeText(value);
      } else {
        const ta = document.createElement("textarea");
        ta.value = value;
        ta.style.position = "fixed";
        ta.style.opacity = "0";
        document.body.appendChild(ta);
        ta.select();
        document.execCommand("copy");
        document.body.removeChild(ta);
      }
      setCopiedField(field);
      setTimeout(() => setCopiedField((c) => (c === field ? null : c)), 1500);
    } catch {
      // Clipboard unavailable or permission denied; silently ignore.
    }
  };

  const { data: request, isLoading } = useGetRequest(params.id || "", {
    query: { enabled: !!params.id, queryKey: getGetRequestQueryKey(params.id || "") },
  });

  const donateMutation = useDonateToRequest();

  const form = useForm<FormData>({
    resolver: zodResolver(schema),
    defaultValues: { donorName: "", donorPhone: "", donorEmail: "" },
  });

  // POC demo stats — stable per case (visits / last-donation time / beneficiaries
  // are not stored by the API, so derive plausible values from the case id).
  const stats = useMemo(() => {
    const h = hashStr(params.id || "case");
    return {
      visits: 8000 + (h % 15000),
      donations: 1500 + ((h >> 3) % 22000),
      beneficiaries: 5 + (h % 30),
      totalBeneficiaries: 60,
      lastDonationSeconds: 11 + (h % 49),
    };
  }, [params.id]);

  if (isLoading) {
    return (
      <div className="container mx-auto px-4 py-12 max-w-5xl space-y-4">
        <Skeleton className="h-10 w-48" />
        <Skeleton className="h-80 w-full" />
      </div>
    );
  }

  if (!request) {
    return (
      <div className="container mx-auto px-4 py-12 text-center text-muted-foreground">
        {t.donate.caseNotFound}
      </div>
    );
  }

  const progress = Math.min(
    100,
    request.requestedAmount > 0
      ? Math.round((request.collectedAmount / request.requestedAmount) * 100)
      : 0
  );
  const remaining = Math.max(0, request.requestedAmount - request.collectedAmount);

  if (donated) {
    return (
      <div className="relative min-h-[70vh] overflow-hidden">
        {/* Faint EHSAN geometric pattern */}
        <div
          aria-hidden="true"
          className="pointer-events-none absolute inset-x-0 top-0 h-72 opacity-[0.06]"
          style={{ backgroundImage: PATTERN_BG, backgroundSize: "120px 120px" }}
        />

        <div className="container relative mx-auto px-4 py-16 max-w-xl text-center">
          {/* Checkmark badge */}
          <div className="mx-auto mb-8 flex h-20 w-20 items-center justify-center rounded-full bg-[#E9F5EF]">
            <Check className="h-9 w-9 text-[#176B43]" strokeWidth={2} />
          </div>

          <h2 className="text-2xl font-bold text-foreground mb-3">{t.donate.successTitle}</h2>
          <p className="text-muted-foreground mb-7">{t.donate.successSubtitle}</p>

          {/* Amount */}
          <div className="mb-9 flex items-center justify-center gap-2 text-4xl font-bold text-[#176B43]">
            <Riyal size="1em" />
            <span>
              {donatedAmount.toLocaleString("en-US", {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2,
              })}
            </span>
          </div>

          {/* Receipt + reference chips */}
          <div className="space-y-4">
            <button
              type="button"
              onClick={() => copyToClipboard(receiptNo, "receipt")}
              data-testid="button-copy-receipt"
              className="group flex w-full items-center justify-between gap-3 rounded-full border border-[#CDE7DA] bg-white px-5 py-3.5 text-start transition-colors hover:bg-[#F4FAF7]"
            >
              <Copy className="h-5 w-5 shrink-0 text-[#176B43]" />
              <span className="flex-1 text-sm text-foreground">
                <span className="text-muted-foreground">{t.donate.receiptNumber}: </span>
                <span className="font-medium">{receiptNo}</span>
              </span>
              {copiedField === "receipt" && (
                <span className="shrink-0 text-xs font-medium text-[#176B43]">{t.donate.copied}</span>
              )}
            </button>

            <button
              type="button"
              onClick={() => copyToClipboard(referenceNo, "reference")}
              data-testid="button-copy-reference"
              className="group flex w-full items-center justify-between gap-3 rounded-2xl border border-[#CDE7DA] bg-white px-5 py-3.5 text-start transition-colors hover:bg-[#F4FAF7]"
            >
              <Copy className="h-5 w-5 shrink-0 text-[#176B43]" />
              <span className="flex-1 text-sm text-foreground">
                <span className="text-muted-foreground">{t.donate.referenceNumber}: </span>
                <span className="font-medium break-all">{referenceNo}</span>
              </span>
              {copiedField === "reference" && (
                <span className="shrink-0 text-xs font-medium text-[#176B43]">{t.donate.copied}</span>
              )}
            </button>
          </div>

          {/* Refund note */}
          <div className="mt-6 flex items-center justify-center gap-2 rounded-xl bg-muted/40 px-5 py-4 text-sm text-muted-foreground">
            <Info className="h-4 w-4 shrink-0" />
            <span>{t.donate.refundNote}</span>
          </div>
        </div>
      </div>
    );
  }

  const goToPayment = () => {
    const amt = Number(amount);
    if (!Number.isFinite(amt) || amt <= 0) {
      setAmountError(true);
      return;
    }
    // Never let a single donation exceed the remaining target.
    if (amt > remaining) {
      setAmount(String(remaining));
    }
    setAmountError(false);
    setStep(2);
  };

  const onSubmit = (data: FormData) => {
    donateMutation.mutate(
      {
        id: params.id || "",
        data: {
          donorName: data.donorName,
          donorPhone: data.donorPhone,
          donorEmail: data.donorEmail || null,
          amount: Number(amount),
        },
      },
      {
        onSuccess: () => {
          queryClient.invalidateQueries({ queryKey: getListRequestsQueryKey() });
          queryClient.invalidateQueries({ queryKey: getListPublishedRequestsQueryKey() });
          queryClient.invalidateQueries({ queryKey: getGetRequestQueryKey(params.id || "") });
          removeFromCart(params.id || "");
          setDonatedAmount(Number(amount));
          setReceiptNo(generateReceiptNo());
          setReferenceNo(generateReferenceNo());
          setDonated(true);
        },
      }
    );
  };

  const StepIndicator = () => (
    <div className="flex items-start justify-center mb-10 w-full max-w-[12rem] mx-auto">
      {/* Step 1 - Details */}
      <div className="flex flex-col items-center gap-1.5 shrink-0">
        <div className={`w-9 h-9 rounded-full flex items-center justify-center text-sm font-bold border-2 ${
          step >= 1 ? "bg-[#176B43] text-white border-[#176B43]" : "bg-background text-muted-foreground border-border"
        }`}>
          {step > 1 ? <Check className="w-4 h-4" /> : "1"}
        </div>
        <span className={`text-xs font-medium ${step >= 1 ? "text-[#176B43]" : "text-muted-foreground"}`}>
          {t.donate.stepDetails}
        </span>
      </div>
      {/* Connector - continuous line aligned to circle centers */}
      <div className={`flex-1 h-0.5 mt-[17px] ${step >= 2 ? "bg-[#176B43]" : "bg-border"}`} />
      {/* Step 2 - Payment */}
      <div className="flex flex-col items-center gap-1.5 shrink-0">
        <div className={`w-9 h-9 rounded-full flex items-center justify-center text-sm font-bold border-2 ${
          step >= 2 ? "bg-[#176B43] text-white border-[#176B43]" : "bg-background text-muted-foreground border-border"
        }`}>
          2
        </div>
        <span className={`text-xs font-medium ${step >= 2 ? "text-[#176B43]" : "text-muted-foreground"}`}>
          {t.donate.stepPayment}
        </span>
      </div>
    </div>
  );

  const DetailsPanel = () => (
    <Card className="overflow-hidden">
      <div className="bg-muted/30 px-5 py-3 border-b">
        <h2 className="font-bold text-foreground">{t.donate.detailsTitle}</h2>
      </div>
      <div className="relative">
        <img
          src={getNeedImage(request.needType)}
          alt={request.description}
          className="w-full h-52 object-cover"
        />
        <div className="absolute bottom-0 inset-x-0 h-6 bg-gray-200 flex">
          <div
            className="h-full bg-primary flex items-center justify-end px-3 text-primary-foreground text-xs font-bold min-w-[3rem]"
            style={{ width: `${progress}%` }}
          >
            {progress}%
          </div>
        </div>
      </div>
      <CardContent className="pt-5 space-y-4">
        <span className="inline-block text-xs font-medium text-muted-foreground border border-border rounded-md px-3 py-1">
          {t.needTypes[request.needType as keyof typeof t.needTypes] || t.opportunities.generalProjects}
        </span>
        <h3 className="text-lg font-bold text-primary leading-snug">{request.description}</h3>
        <p className="text-xs font-mono text-muted-foreground">{request.caseId}</p>
        <div className="grid grid-cols-2 gap-2 bg-muted/40 rounded-xl p-4">
          <div className="text-center border-s border-border">
            <p className="text-sm text-primary mb-1">{t.opportunities.remainingShort}</p>
            <p className="font-bold text-foreground inline-flex items-center gap-1">{remaining.toLocaleString()} <Riyal /></p>
          </div>
          <div className="text-center">
            <p className="text-sm text-primary mb-1">{t.opportunities.collectedShort}</p>
            <p className="font-bold text-foreground inline-flex items-center gap-1">{request.collectedAmount.toLocaleString()} <Riyal /></p>
          </div>
        </div>
      </CardContent>
    </Card>
  );

  return (
    <div className="container mx-auto px-4 py-12 max-w-5xl">
      <StepIndicator />

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 items-start">
        {/* Details panel (right in RTL) */}
        <DetailsPanel />

        {/* Form panel (left in RTL) */}
        {step === 1 ? (
          <Card>
            <div className="bg-muted/30 px-5 py-3 border-b">
              <h2 className="font-bold text-foreground">{t.donate.amountTitle}</h2>
            </div>
            <CardContent className="pt-5 space-y-5">
              {/* Presets */}
              <div className="grid grid-cols-3 gap-3">
                {PRESETS.map((p) => (
                  <button
                    key={p}
                    type="button"
                    onClick={() => { setAmount(String(p)); setAmountError(false); }}
                    className={`py-3 rounded-lg border text-sm font-bold transition-colors ${
                      Number(amount) === p
                        ? "bg-primary text-primary-foreground border-primary"
                        : "bg-background border-border text-foreground hover:border-primary"
                    }`}
                    data-testid={`preset-${p}`}
                  >
                    <span className="inline-flex items-center justify-center gap-1">{p} <Riyal /></span>
                  </button>
                ))}
              </div>

              {/* Custom amount */}
              <div className="relative">
                <span className="absolute start-3 top-1/2 -translate-y-1/2 text-muted-foreground text-sm pointer-events-none">
                  <Riyal />
                </span>
                <Input
                  type="number"
                  min={1}
                  value={amount}
                  onChange={(e) => { setAmount(e.target.value); setAmountError(false); }}
                  placeholder={t.donate.customAmount}
                  className="ps-8"
                  data-testid="input-customAmount"
                />
              </div>

              {/* On behalf checkbox */}
              <div className="flex items-start gap-2">
                <Gift className="w-5 h-5 text-primary shrink-0 mt-0.5" />
                <div className="flex-1">
                  <label className="flex items-center gap-2 cursor-pointer">
                    <Checkbox
                      checked={onBehalf}
                      onCheckedChange={(v) => setOnBehalf(v === true)}
                      data-testid="checkbox-onBehalf"
                    />
                    <span className="text-sm text-foreground">{t.donate.onBehalf}</span>
                  </label>
                  {onBehalf && (
                    <Input
                      value={onBehalfName}
                      onChange={(e) => setOnBehalfName(e.target.value)}
                      placeholder={t.donate.onBehalfName}
                      className="mt-3"
                      data-testid="input-onBehalfName"
                    />
                  )}
                </div>
              </div>

              {amountError && (
                <p className="text-sm text-destructive" data-testid="text-amountError">
                  {t.donate.selectAmountError}
                </p>
              )}

              <Button
                className="w-full"
                onClick={goToPayment}
                data-testid="button-continueToPayment"
              >
                {t.donate.donateNow}
              </Button>
            </CardContent>
          </Card>
        ) : (
          <Card>
            <div className="bg-muted/30 px-5 py-3 border-b">
              <h2 className="font-bold text-foreground">{t.donate.paymentTitle}</h2>
            </div>
            <CardContent className="pt-5">
              <div className="flex items-center justify-between bg-primary/5 rounded-lg px-4 py-3 mb-5">
                <span className="text-sm text-muted-foreground">{t.donate.amount}</span>
                <span className="text-lg font-bold text-primary inline-flex items-center gap-1">{Number(amount).toLocaleString()} <Riyal /></span>
              </div>
              <Form {...form}>
                <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-5">
                  <FormField
                    control={form.control}
                    name="donorName"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>{t.donate.donorName}</FormLabel>
                        <FormControl>
                          <Input data-testid="input-donorName" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="donorPhone"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>{t.donate.donorPhone}</FormLabel>
                        <FormControl>
                          <Input data-testid="input-donorPhone" type="tel" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="donorEmail"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>{t.donate.donorEmail}</FormLabel>
                        <FormControl>
                          <Input data-testid="input-donorEmail" type="email" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <div className="flex gap-3">
                    <Button
                      type="button"
                      variant="outline"
                      className="flex-1"
                      onClick={() => setStep(1)}
                      data-testid="button-backToDetails"
                    >
                      {t.donate.backToDetails}
                    </Button>
                    <Button
                      type="submit"
                      className="flex-1"
                      disabled={donateMutation.isPending}
                      data-testid="button-confirmDonation"
                    >
                      {donateMutation.isPending ? t.common.loading : t.donate.confirmDonation}
                    </Button>
                  </div>
                </form>
              </Form>
            </CardContent>
          </Card>
        )}
      </div>

      {/* Case stat cards (POC demo values) */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-8">
        {[
          {
            icon: Eye,
            label: t.donate.statsVisits,
            value: stats.visits.toLocaleString("en-US"),
            unit: t.donate.statsVisitsUnit,
          },
          {
            icon: Clock,
            label: t.donate.statsLastDonation,
            value: stats.lastDonationSeconds.toLocaleString("en-US"),
            unit: t.donate.statsSecondUnit,
          },
          {
            icon: Users,
            label: t.donate.statsBeneficiaries,
            value: stats.beneficiaries.toLocaleString("en-US"),
            unit: `${t.donate.statsOutOf} ${stats.totalBeneficiaries.toLocaleString("en-US")}`,
          },
          {
            icon: Radio,
            label: t.donate.statsDonations,
            value: stats.donations.toLocaleString("en-US"),
            unit: t.donate.statsDonationsUnit,
          },
        ].map(({ icon: Icon, label, value, unit }) => (
          <div
            key={label}
            className="flex items-center gap-4 rounded-2xl border border-gray-200 bg-white px-5 py-4"
          >
            <div className="flex-1 min-w-0 text-center">
              <p className="text-sm text-[#1B8354] mb-1.5">{label}</p>
              <p className="flex items-baseline justify-center gap-1.5 flex-wrap font-bold text-foreground text-xl">
                <span>{value}</span>
                <span className="text-xs font-normal text-[#1B8354]">{unit}</span>
              </p>
            </div>
            <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-[#EAF5EF] text-[#1B8354]">
              <Icon className="h-[18px] w-[18px]" />
            </div>
          </div>
        ))}
      </div>

      <div className="mt-6 text-center">
        <Link href="/opportunities">
          <Button variant="ghost" size="sm">{t.common.back}</Button>
        </Link>
      </div>
    </div>
  );
}
