"use client";

import { Crown, Lightning } from '@/lib/icons';
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import type { PlanUsage } from "@/lib/appwrite/plan-limits";
import type { TenantPlan } from "@/lib/appwrite/schema";
import { RESOURCE_LABELS } from "@/lib/appwrite/plan-limits-shared";

const LIMIT_LABELS: Record<string, string> = {
  properties: "İlan",
  customers: "Müşteri",
  members: "Ekip üyesi",
  presentations: "Sunum",
};

export function CurrentPlanCard({
  plan,
  expiresAt,
  usage,
}: {
  plan: TenantPlan;
  expiresAt: string | null;
  usage: PlanUsage["usage"];
}) {
  const isPro = plan === "pro";
  const expiryDate = expiresAt ? new Date(expiresAt).toLocaleDateString("tr-TR") : null;

  return (
    <Card>
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <CardTitle className="text-base font-semibold">Mevcut Plan</CardTitle>
          <Badge
            variant={isPro ? "default" : "secondary"}
            className="gap-1"
          >
            {isPro ? <Crown className="h-3 w-3" /> : <Lightning className="h-3 w-3" />}
            {isPro ? "Pro" : "Ücretsiz"}
          </Badge>
        </div>
        {isPro && expiryDate && (
          <p className="text-xs text-muted-foreground">{expiryDate} tarihine kadar geçerli</p>
        )}
      </CardHeader>
      <CardContent className="space-y-3">
        {(Object.entries(usage) as [keyof typeof usage, PlanUsage["usage"][keyof PlanUsage["usage"]]][]).map(
          ([resource, { used, limit, reached }]) => {
            const isUnlimited = limit === Number.POSITIVE_INFINITY;
            const pct = isUnlimited ? 0 : Math.min(100, (used / limit) * 100);
            return (
              <div key={resource} className="space-y-1">
                <div className="flex justify-between text-xs text-muted-foreground">
                  <span>{LIMIT_LABELS[resource] ?? RESOURCE_LABELS[resource as keyof typeof RESOURCE_LABELS]}</span>
                  <span className={reached && !isUnlimited ? "text-destructive font-medium" : ""}>
                    {isUnlimited ? `${used} / ∞` : `${used} / ${limit}`}
                  </span>
                </div>
                {!isUnlimited && (
                  <Progress
                    value={pct}
                    className={`h-1.5 ${reached ? "[&>div]:bg-destructive" : ""}`}
                  />
                )}
              </div>
            );
          }
        )}
      </CardContent>
    </Card>
  );
}
