import { useParams, useLocation } from "wouter";
import { useLanguage } from "../contexts/LanguageContext";
import { useGetRequest, getGetRequestQueryKey } from "@workspace/api-client-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Check, Clock } from "lucide-react";
import { Link } from "wouter";

const STEPS = [
  "step1", "step2", "step3", "step4", "step5",
  "step6", "step7", "step8", "step9", "step10",
] as const;

const STATUS_TO_STEP: Record<string, number> = {
  new: 1,
  pending_review: 2,
  verified: 3,
  published: 4,
  donated: 5,
  delivered: 6,
  receipt_confirmed: 7,
  thank_you_submitted: 8,
  whatsapp_sent: 9,
  closed: 10,
  rejected: 2,
};

export default function Track() {
  const { t } = useLanguage();
  const params = useParams<{ id: string }>();
  const [, setLocation] = useLocation();

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

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

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

  const currentStep = STATUS_TO_STEP[request.status] || 1;
  const isRejected = request.status === "rejected";

  return (
    <div className="container mx-auto px-4 py-12 max-w-3xl">
      <div className="mb-8 flex items-center justify-between flex-wrap gap-4">
        <div>
          <h1 className="text-3xl font-bold text-foreground">{t.track.title}</h1>
          <p className="text-muted-foreground mt-1">
            {request.caseId} — {request.beneficiaryName}
          </p>
        </div>
        <Badge
          className={`text-sm px-3 py-1 ${
            isRejected
              ? "bg-red-100 text-red-700 border-red-200"
              : request.status === "closed"
              ? "bg-green-100 text-green-700 border-green-200"
              : "bg-amber-100 text-amber-700 border-amber-200"
          }`}
          variant="outline"
        >
          {t.statuses[request.status as keyof typeof t.statuses] || request.status}
        </Badge>
      </div>

      {/* Case Info */}
      <Card className="mb-8 bg-muted/30">
        <CardHeader className="pb-2">
          <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
            {t.track.caseInfo}
          </CardTitle>
        </CardHeader>
        <CardContent className="pt-0">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
            <div>
              <p className="text-muted-foreground text-xs uppercase tracking-wide mb-1">
                {t.request.needType}
              </p>
              <p className="font-semibold">
                {t.needTypes[request.needType as keyof typeof t.needTypes]}
              </p>
            </div>
            <div>
              <p className="text-muted-foreground text-xs uppercase tracking-wide mb-1">
                {t.request.amount}
              </p>
              <p className="font-semibold">{request.requestedAmount.toLocaleString()} ﷼</p>
            </div>
            <div>
              <p className="text-muted-foreground text-xs uppercase tracking-wide mb-1">
                {t.opportunities.collected}
              </p>
              <p className="font-semibold text-primary">{request.collectedAmount.toLocaleString()} ﷼</p>
            </div>
            {request.donorName && (
              <div>
                <p className="text-muted-foreground text-xs uppercase tracking-wide mb-1">
                  {t.whatsapp.donor}
                </p>
                <p className="font-semibold">{request.donorName}</p>
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Timeline */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base font-semibold">{t.track.caseTimeline}</CardTitle>
        </CardHeader>
        <CardContent>
          {isRejected ? (
            <div className="p-6 text-center bg-red-50 rounded-lg border border-red-200">
              <p className="text-red-700 font-semibold mb-2">{t.track.rejected}</p>
              {request.rejectionReason && (
                <p className="text-red-600 text-sm">{request.rejectionReason}</p>
              )}
            </div>
          ) : (
            <div className="relative">
              {STEPS.map((stepKey, index) => {
                const stepNum = index + 1;
                const isDone = stepNum < currentStep;
                const isCurrent = stepNum === currentStep;

                return (
                  <div key={stepKey} className="flex items-start gap-4 mb-6 last:mb-0">
                    <div className="flex flex-col items-center">
                      <div
                        className={`w-9 h-9 rounded-full flex items-center justify-center flex-shrink-0 border-2 transition-all ${
                          isDone
                            ? "bg-primary border-primary text-white"
                            : isCurrent
                            ? "bg-primary/10 border-primary text-primary"
                            : "bg-muted border-border text-muted-foreground"
                        }`}
                        data-testid={`step-icon-${stepNum}`}
                      >
                        {isDone ? (
                          <Check className="w-4 h-4" />
                        ) : isCurrent ? (
                          <Clock className="w-4 h-4" />
                        ) : (
                          <span className="text-xs font-semibold">{stepNum}</span>
                        )}
                      </div>
                      {index < STEPS.length - 1 && (
                        <div
                          className={`w-0.5 h-6 mt-1 ${isDone ? "bg-primary" : "bg-border"}`}
                        />
                      )}
                    </div>
                    <div className="pt-1.5">
                      <p
                        className={`font-medium text-sm ${
                          isDone
                            ? "text-primary"
                            : isCurrent
                            ? "text-foreground"
                            : "text-muted-foreground"
                        }`}
                      >
                        {t.workflow[stepKey as keyof typeof t.workflow]}
                      </p>
                      {isCurrent && (
                        <p className="text-xs text-primary mt-0.5 font-medium">
                          ● {t.track.currentStepLabel}
                        </p>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Actions */}
      <div className="mt-6 flex gap-3 flex-wrap">
        {request.status === "receipt_confirmed" && (
          <Link href={`/thank-you/${request.id}`}>
            <Button data-testid="button-submitThankYou">
              {t.track.submitThankYou}
            </Button>
          </Link>
        )}
        <Button variant="outline" onClick={() => setLocation("/admin")}>
          {t.common.adminDashboard}
        </Button>
        <Button variant="ghost" onClick={() => setLocation("/opportunities")}>
          {t.common.back}
        </Button>
      </div>
    </div>
  );
}
