"use client";

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

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

function PlanIcon({ plan }: { plan: TenantPlan }) {
  if (plan === "enterprise") return <Crown className="h-4 w-4" />;
  if (plan === "pro") return <Star className="h-4 w-4" />;
  if (plan === "starter") return <Lightning className="h-4 w-4" />;
  return <Lightning className="h-4 w-4" />;
}

function planBadgeVariant(plan: TenantPlan): "default" | "secondary" | "outline" {
  if (plan === "enterprise" || plan === "pro") return "default";
  if (plan === "starter") return "outline";
  return "secondary";
}

export function CurrentPlanCard({
  plan,
  period,
  expiresAt,
  usage,
}: {
  plan: TenantPlan;
  period?: PlanPeriod | null;
  expiresAt: string | null;
  usage: PlanUsage["usage"];
}) {
  const isPaid = plan !== "free";
  const expiryDate = expiresAt ? new Date(expiresAt).toLocaleDateString("tr-TR") : null;
  const periodLabel = period === "yearly" ? "Yıllık" : period === "monthly" ? "Aylık" : null;

  return (
    <Card>
      <CardContent className="pt-4">
        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          {/* Plan bilgisi */}
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10 text-primary shrink-0">
              <PlanIcon plan={plan} />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <span className="font-semibold text-sm">{PLAN_NAMES[plan]} Plan</span>
                <Badge variant={planBadgeVariant(plan)} className="gap-1 text-[11px]">
                  <PlanIcon plan={plan} />
                  {PLAN_NAMES[plan]}
                  {periodLabel && <span className="opacity-70">· {periodLabel}</span>}
                </Badge>
              </div>
              {isPaid && expiryDate && (
                <p className="text-xs text-muted-foreground mt-0.5">
                  {expiryDate} tarihine kadar geçerli
                </p>
              )}
              {!isPaid && (
                <p className="text-xs text-muted-foreground mt-0.5">
                  Ücretsiz kullanımdaki özellikler
                </p>
              )}
            </div>
          </div>

          {/* Kullanım çubukları */}
          <div className="grid grid-cols-2 gap-x-8 gap-y-2 sm:grid-cols-4">
            {(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="min-w-[80px]">
                    <div className="flex justify-between text-[11px] text-muted-foreground mb-1">
                      <span>{RESOURCE_LABELS[resource] ?? resource}</span>
                      <span className={reached && !isUnlimited ? "text-destructive font-medium" : ""}>
                        {isUnlimited ? `${used}/∞` : `${used}/${limit}`}
                      </span>
                    </div>
                    {isUnlimited ? (
                      <div className="h-1 rounded-full bg-primary/20" />
                    ) : (
                      <Progress
                        value={pct}
                        className={`h-1 ${reached ? "[&>div]:bg-destructive" : ""}`}
                      />
                    )}
                  </div>
                );
              }
            )}
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
