import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useParams, useLocation } 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, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { CheckCircle, Heart } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
import { Link } from "wouter";

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

type FormData = z.infer<typeof schema>;

export default function Donate() {
  const { t } = useLanguage();
  const params = useParams<{ id: string }>();
  const [, setLocation] = useLocation();
  const queryClient = useQueryClient();
  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: "",
      amount: 0,
    },
  });

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

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

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

  if (donated) {
    return (
      <div className="container mx-auto px-4 py-12 max-w-2xl">
        <Card className="border-2 border-green-200">
          <CardContent className="pt-10 pb-10 text-center">
            <Heart className="w-16 h-16 text-green-600 mx-auto mb-4 fill-green-100" />
            <CheckCircle className="w-10 h-10 text-green-500 mx-auto mb-4" />
            <h2 className="text-2xl font-bold text-green-700 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 progress = Math.min(
    100,
    request.requestedAmount > 0
      ? Math.round((request.collectedAmount / request.requestedAmount) * 100)
      : 0
  );

  return (
    <div className="container mx-auto px-4 py-12 max-w-2xl">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-foreground">{t.donate.title}</h1>
      </div>

      {/* Case Summary */}
      <Card className="mb-6 bg-primary/5 border-primary/20">
        <CardHeader className="pb-2">
          <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
            {t.donate.caseSummary}
          </CardTitle>
        </CardHeader>
        <CardContent className="pt-0">
          <div className="flex justify-between items-start mb-3">
            <div>
              <p className="font-semibold text-foreground">{request.description}</p>
              <p className="text-sm text-muted-foreground mt-1">{request.caseId}</p>
            </div>
            <Badge className="bg-primary/10 text-primary border-primary/20">
              {t.needTypes[request.needType as keyof typeof t.needTypes]}
            </Badge>
          </div>
          <div className="flex justify-between text-sm mb-2">
            <span className="text-muted-foreground">
              {t.opportunities.collected}:{" "}
              <strong>{request.collectedAmount.toLocaleString()} ﷼</strong>
            </span>
            <span className="text-muted-foreground">
              {t.opportunities.target}:{" "}
              <strong>{request.requestedAmount.toLocaleString()} ﷼</strong>
            </span>
          </div>
          <Progress value={progress} className="h-2" />
        </CardContent>
      </Card>

      {/* Donation Form */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg font-semibold text-primary">{t.donate.title}</CardTitle>
        </CardHeader>
        <CardContent>
          <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>
                )}
              />
              <FormField
                control={form.control}
                name="amount"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t.donate.amount} (﷼)</FormLabel>
                    <FormControl>
                      <Input data-testid="input-donationAmount" type="number" min={1} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <Button
                type="submit"
                className="w-full"
                disabled={donateMutation.isPending}
                data-testid="button-confirmDonation"
              >
                {donateMutation.isPending ? t.common.loading : t.donate.confirmDonation}
              </Button>
            </form>
          </Form>
        </CardContent>
      </Card>

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