import { useState } from "react";
import { useLanguage } from "../contexts/LanguageContext";
import { useGetStats, useListPublishedRequests } from "@workspace/api-client-react";
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { Skeleton } from "@/components/ui/skeleton";
import { Link } from "wouter";
import { Search } from "lucide-react";

export default function Home() {
  const { t } = useLanguage();
  const { data: stats, isLoading: statsLoading } = useGetStats();
  const { data: published, isLoading: pubLoading } = useListPublishedRequests();
  const [query, setQuery] = useState("");

  const filtered = (published || []).filter((r) => {
    if (!query.trim()) return true;
    const q = query.toLowerCase();
    return (
      r.caseId.toLowerCase().includes(q) ||
      r.description.toLowerCase().includes(q) ||
      r.beneficiaryName.toLowerCase().includes(q)
    );
  });

  return (
    <div className="container mx-auto px-4 py-12">
      {/* Hero */}
      <section className="text-center py-16 bg-primary/5 rounded-3xl mb-12 border border-primary/10 px-6">
        <h1 className="text-4xl md:text-5xl font-bold text-primary mb-6">
          {t.home.heroTitle}
        </h1>
        <p className="text-xl text-muted-foreground max-w-2xl mx-auto mb-8">
          {t.home.heroSubtitle}
        </p>

        {/* Search Bar */}
        <div className="max-w-xl mx-auto">
          <label className="block text-sm font-medium text-foreground mb-2">
            {t.home.searchLabel}
          </label>
          <div className="flex gap-2">
            <div className="relative flex-1">
              <Search className="absolute start-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
              <Input
                className="ps-9"
                placeholder={t.common.searchPlaceholder}
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                data-testid="input-search"
              />
            </div>
            <Button data-testid="button-search">{t.home.searchButton}</Button>
          </div>
        </div>
      </section>

      {/* Stats */}
      {statsLoading ? (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-16">
          <Skeleton className="h-32 w-full" />
          <Skeleton className="h-32 w-full" />
          <Skeleton className="h-32 w-full" />
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-16">
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                {t.home.totalRequests}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-4xl font-bold text-foreground">
                {stats?.totalRequests || 0}
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                {t.home.totalCollected}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-4xl font-bold text-primary">
                {stats?.totalCollected?.toLocaleString() || 0} ﷼
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                {t.home.totalClosed}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-4xl font-bold text-foreground">
                {stats?.totalClosed || 0}
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Featured Opportunities */}
      <section className="mb-16">
        <div className="flex items-center justify-between mb-6 flex-wrap gap-3">
          <h2 className="text-2xl font-bold">{t.home.featuredTitle}</h2>
          <Link href="/opportunities">
            <Button variant="outline" size="sm">{t.home.viewOpportunities}</Button>
          </Link>
        </div>

        {pubLoading ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {[1, 2, 3].map((i) => <Skeleton key={i} className="h-64 w-full" />)}
          </div>
        ) : filtered.length === 0 ? (
          <div className="col-span-full text-center py-12 text-muted-foreground bg-muted/20 rounded-xl border border-dashed">
            {query.trim() ? t.home.noResults : t.opportunities.noOpportunities}
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {filtered.slice(0, 6).map((request) => {
              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);
              return (
                <Card key={request.id} className="overflow-hidden flex flex-col">
                  <CardHeader className="bg-primary/5 pb-4 border-b">
                    <div className="flex justify-between items-start mb-2">
                      <Badge variant="outline" className="bg-white">
                        {t.needTypes[request.needType as keyof typeof t.needTypes] || request.needType}
                      </Badge>
                      <Badge className="bg-green-600 text-white">
                        {t.opportunities.verified}
                      </Badge>
                    </div>
                    <CardTitle className="text-base line-clamp-2">{request.description}</CardTitle>
                    <p className="text-xs font-mono text-muted-foreground">{request.caseId}</p>
                  </CardHeader>
                  <CardContent className="pt-5 flex-1">
                    <div className="flex justify-between text-sm mb-2">
                      <span className="text-muted-foreground">
                        {t.opportunities.collected}:{" "}
                        <strong className="text-foreground">{request.collectedAmount.toLocaleString()} ﷼</strong>
                      </span>
                      <span className="text-muted-foreground">
                        {t.opportunities.target}:{" "}
                        <strong className="text-foreground">{request.requestedAmount.toLocaleString()} ﷼</strong>
                      </span>
                    </div>
                    <Progress value={progress} className="h-2 mb-2" />
                    <div className="text-sm font-medium text-primary">{progress}%</div>
                    <div className="mt-3 text-center">
                      <span className="text-sm text-muted-foreground">{t.opportunities.remaining}: </span>
                      <span className="font-bold text-lg">{remaining.toLocaleString()} ﷼</span>
                    </div>
                  </CardContent>
                  <CardFooter className="pt-0">
                    <Link href={`/donate/${request.id}`} className="w-full">
                      <Button className="w-full" disabled={remaining <= 0}>
                        {t.opportunities.donate}
                      </Button>
                    </Link>
                  </CardFooter>
                </Card>
              );
            })}
          </div>
        )}
      </section>

      {/* Workflow Steps */}
      <section className="mb-12">
        <h2 className="text-2xl font-bold mb-8 text-center">{t.home.workflowTitle}</h2>
        <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
          {Array.from({ length: 10 }).map((_, i) => (
            <Card key={i} className="bg-muted/50 border-none shadow-none">
              <CardContent className="p-4 text-center">
                <div className="w-8 h-8 rounded-full bg-primary/20 text-primary mx-auto flex items-center justify-center font-bold mb-3 text-sm">
                  {i + 1}
                </div>
                <div className="text-sm font-medium">
                  {t.workflow[`step${i + 1}` as keyof typeof t.workflow]}
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      </section>
    </div>
  );
}
