import { useState } from "react";
import { useLocation } from "wouter";
import { useLanguage } from "../contexts/LanguageContext";
import { useCart } from "../contexts/CartContext";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Share2, ShoppingCart } from "lucide-react";
import { getNeedImage } from "../lib/needImages";
import { Riyal } from "@/components/Riyal";

interface OpportunityCardProps {
  request: {
    id: string;
    caseId: string;
    description: string;
    needType: string;
    requestedAmount: number;
    collectedAmount: number;
  };
}

export function OpportunityCard({ request }: OpportunityCardProps) {
  const { t } = useLanguage();
  const [, setLocation] = useLocation();
  const { addItem, removeItem, isInCart } = useCart();
  const [amount, setAmount] = useState("");

  const inCart = isInCart(request.id);

  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);
  const isComplete = remaining <= 0;

  const goDonate = () => {
    const amt = Number(amount);
    const suffix = amt > 0 ? `?amount=${amt}` : "";
    setLocation(`/donate/${request.id}${suffix}`);
  };

  const handleAddToCart = () => {
    addItem(
      {
        id: request.id,
        caseId: request.caseId,
        description: request.description,
        needType: request.needType,
        requestedAmount: request.requestedAmount,
        collectedAmount: request.collectedAmount,
      },
      Number(amount)
    );
  };

  return (
    <div className="bg-card rounded-2xl border border-card-border shadow-sm overflow-hidden flex flex-col h-full hover-elevate">
      {/* Photo + progress bar */}
      <div className="relative">
        <img
          src={getNeedImage(request.needType)}
          alt={request.description}
          className="w-full h-44 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>

      <div className="p-4 flex flex-col flex-1">
        {/* Category badge */}
        <div className="flex justify-start mb-3">
          <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>
        </div>

        {/* Title + share */}
        <div className="flex items-start justify-between gap-3 mb-4">
          <h3 className="text-base font-bold text-primary leading-snug line-clamp-2 flex-1">
            {request.description}
          </h3>
          <Share2 className="w-4 h-4 text-muted-foreground shrink-0 mt-1" />
        </div>

        {/* Collected / Remaining */}
        <div className="grid grid-cols-2 gap-2 bg-muted/40 rounded-xl p-4 mb-4 mt-auto">
          <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>

        {/* Donate / cart row */}
        {inCart ? (
          <div
            className="flex items-center justify-between gap-3 rounded-lg bg-muted/70 px-4 py-3"
            data-testid={`added-state-${request.id}`}
          >
            <span className="text-sm font-medium text-primary">
              {t.cart.added}
            </span>
            <button
              type="button"
              onClick={() => removeItem(request.id)}
              className="text-sm font-medium text-foreground hover:text-destructive transition-colors"
              data-testid={`button-removeFromCart-${request.id}`}
            >
              {t.cart.remove}
            </button>
          </div>
        ) : (
          <div className="flex items-stretch gap-2">
            <Button
              variant="outline"
              size="icon"
              className="shrink-0"
              onClick={handleAddToCart}
              disabled={isComplete}
              aria-label={t.cart.addToCart}
              data-testid={`button-cart-${request.id}`}
            >
              <ShoppingCart className="w-4 h-4" />
            </Button>
            <Button
              className="shrink-0 px-5"
              onClick={goDonate}
              disabled={isComplete}
              data-testid={`button-donate-${request.id}`}
            >
              {t.opportunities.donate}
            </Button>
            <div className="relative flex-1">
              <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)}
                placeholder={t.opportunities.amountPlaceholder}
                className="ps-8 h-full"
                disabled={isComplete}
                data-testid={`input-cardAmount-${request.id}`}
              />
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
