import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useParams, useLocation, useSearch, Link } from "wouter";
import { useLanguage } from "../contexts/LanguageContext";
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 { CheckCircle, Heart, Gift, ShoppingCart, Check } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
import { getNeedImage } from "../lib/needImages";

const RIYAL = "﷼";
const PRESETS = [100, 50, 10];

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 [, setLocation] = useLocation();
  const queryClient = useQueryClient();

  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 { 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: "" },
  });

  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="container mx-auto px-4 py-12 max-w-2xl">
        <Card className="border-2 border-primary/20">
          <CardContent className="pt-10 pb-10 text-center">
            <Heart className="w-16 h-16 text-primary mx-auto mb-4 fill-primary/10" />
            <CheckCircle className="w-10 h-10 text-primary mx-auto mb-4" />
            <h2 className="text-2xl font-bold text-primary mb-2">{t.common.success}</h2>
            <p className="text-muted-foreground text-lg mb-6">{t.donate.successMessage}</p>
            <p className="text-sm font-mono text-muted-foreground bg-muted/30 px-4 py-2 rounded-lg inline-block">
              {request.caseId}
            </p>
            <div className="mt-8 flex gap-3 justify-center">
              <Button variant="outline" onClick={() => setLocation("/opportunities")}>
                {t.common.opportunities}
              </Button>
              <Button onClick={() => setLocation(`/track/${request.id}`)}>
                {t.common.trackCase}
              </Button>
            </div>
          </CardContent>
        </Card>
      </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 || "") });
          setDonated(true);
        },
      }
    );
  };

  const StepIndicator = () => (
    <div className="flex items-center justify-center gap-4 mb-10">
      {/* Step 1 - Details */}
      <div className="flex flex-col items-center gap-1.5">
        <div className={`w-9 h-9 rounded-full flex items-center justify-center text-sm font-bold border-2 ${
          step >= 1 ? "bg-primary text-primary-foreground border-primary" : "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-primary" : "text-muted-foreground"}`}>
          {t.donate.stepDetails}
        </span>
      </div>
      <div className={`h-0.5 w-16 rounded ${step >= 2 ? "bg-primary" : "bg-border"}`} />
      {/* Step 2 - Payment */}
      <div className="flex flex-col items-center gap-1.5">
        <div className={`w-9 h-9 rounded-full flex items-center justify-center text-sm font-bold border-2 ${
          step >= 2 ? "bg-primary text-primary-foreground border-primary" : "bg-background text-muted-foreground border-border"
        }`}>
          2
        </div>
        <span className={`text-xs font-medium ${step >= 2 ? "text-primary" : "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">{RIYAL} {remaining.toLocaleString()}</p>
          </div>
          <div className="text-center">
            <p className="text-sm text-primary mb-1">{t.opportunities.collectedShort}</p>
            <p className="font-bold text-foreground">{RIYAL} {request.collectedAmount.toLocaleString()}</p>
          </div>
        </div>
      </CardContent>
    </Card>
  );

  return (
    <div className="container mx-auto px-4 py-12 max-w-5xl">
      <h1 className="text-3xl font-bold text-foreground mb-8 text-center">{t.donate.title}</h1>
      <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}`}
                  >
                    {RIYAL} {p}
                  </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 gap-2"
                onClick={goToPayment}
                data-testid="button-continueToPayment"
              >
                <ShoppingCart className="w-4 h-4" />
                {t.donate.continueToPayment}
              </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">{RIYAL} {Number(amount).toLocaleString()}</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>

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