import { redirect } from "next/navigation";
import { Building2, Check, Clock, Crown, Sparkles, Stethoscope } from "lucide-react";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { cn } from "@/lib/utils";
import {
  RESOURCE_LABELS,
  getEffectivePlan,
  getPlanUsage,
  type PlanResource,
} from "@/lib/appwrite/plan-limits";
import {
  downgradeToFreeAction,
  startCheckoutAction,
} from "@/lib/appwrite/subscription-actions";
import { isShopierEnabled } from "@/lib/payments/shopier";
import { PLAN_CATALOG } from "@/lib/appwrite/subscription-types";
import { requireTenant } from "@/lib/appwrite/tenant-guard";

const trFmt = new Intl.NumberFormat("tr-TR", {
  style: "currency",
  currency: "TRY",
  maximumFractionDigits: 0,
});

type EcosystemTier = {
  id: "klinik" | "ajans";
  name: string;
  description: string;
  Icon: typeof Stethoscope;
  features: string[];
};

const ECOSYSTEM_TIERS: EcosystemTier[] = [
  {
    id: "klinik",
    name: "Kliniğim",
    description: "Hekim, klinik ve sağlık merkezleri için.",
    Icon: Stethoscope,
    features: [
      "Hasta kaydı + KVKK uyumlu dosyalama",
      "Randevu + hatırlatma",
      "Reçete ve tetkik takibi",
      "Klinik finans paneli",
    ],
  },
  {
    id: "ajans",
    name: "Ajansım",
    description: "Yaratıcı ajanslar ve danışmanlıklar için.",
    Icon: Building2,
    features: [
      "Proje + saat takibi",
      "Müşteri portalı",
      "Brief + onay akışı",
      "Ajans bazlı raporlama",
    ],
  },
];

export default async function PricingPage() {
  let ctx;
  try {
    ctx = await requireTenant();
  } catch {
    redirect("/onboarding");
  }

  const currentPlan = getEffectivePlan(ctx);
  const isPro = currentPlan === "pro";
  const canManage = ctx.role === "owner";
  const usage = await getPlanUsage(ctx);
  const shopierActive = isShopierEnabled();

  const resources: PlanResource[] = ["customers", "financeEntries", "software", "members"];

  const tiers = [
    {
      ...PLAN_CATALOG.free,
      isCurrent: !isPro,
      isPopular: false,
    },
    {
      ...PLAN_CATALOG.pro,
      isCurrent: isPro,
      isPopular: true,
    },
  ];

  return (
    <div className="flex-1 space-y-8 px-6 pt-0">
      <div className="flex flex-col gap-1">
        <p className="text-muted-foreground text-sm">{ctx.settings?.companyName ?? "Çalışma alanı"}</p>
        <h1 className="text-2xl font-bold tracking-tight">Plan</h1>
        <p className="text-muted-foreground text-sm">
          İşletmem'i ölçeğine göre kullan. Sektörel paketler (Kliniğim, Ajansım) yakında.
        </p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">Bu ayki kullanımın</CardTitle>
          <CardDescription>
            Mevcut planın sınırlarına ne kadar yaklaştığını gör.
          </CardDescription>
        </CardHeader>
        <CardContent className="grid gap-4 sm:grid-cols-2">
          {resources.map((r) => {
            const u = usage.usage[r];
            const pct =
              u.limit === Number.POSITIVE_INFINITY
                ? 0
                : Math.min(100, Math.round((u.used / Math.max(1, u.limit)) * 100));
            const limitLabel =
              u.limit === Number.POSITIVE_INFINITY ? "∞" : String(u.limit);
            return (
              <div key={r} className="space-y-1.5">
                <div className="flex items-center justify-between text-sm">
                  <span className="capitalize">{RESOURCE_LABELS[r]}</span>
                  <span
                    className={cn(
                      "font-mono text-xs",
                      u.reached
                        ? "text-destructive font-semibold"
                        : "text-muted-foreground",
                    )}
                  >
                    {u.used} / {limitLabel}
                  </span>
                </div>
                {u.limit !== Number.POSITIVE_INFINITY && (
                  <Progress value={pct} className="h-1.5" />
                )}
              </div>
            );
          })}
        </CardContent>
      </Card>

      <section className="space-y-3">
        <div className="flex items-center justify-between">
          <h2 className="text-lg font-semibold tracking-tight">İşletmem planları</h2>
          <Badge variant="outline" className="text-xs">
            Tek para birimi: ₺ (TRY)
          </Badge>
        </div>

        <div className="grid gap-6 lg:grid-cols-2">
          {tiers.map((tier) => (
            <Card
              key={tier.id}
              className={cn("flex flex-col pt-0", {
                "border-primary relative shadow-lg": tier.isPopular,
                "border-primary": tier.isCurrent,
              })}
            >
              {tier.isCurrent && (
                <div className="absolute start-0 -top-3 w-full">
                  <Badge className="mx-auto flex w-fit gap-1.5 rounded-full font-medium">
                    <Sparkles className="!size-4" />
                    Mevcut plan
                  </Badge>
                </div>
              )}
              {tier.isPopular && !tier.isCurrent && (
                <div className="absolute start-0 -top-3 w-full">
                  <Badge variant="secondary" className="mx-auto flex w-fit gap-1.5 rounded-full font-medium">
                    <Crown className="!size-4" />
                    Önerilen
                  </Badge>
                </div>
              )}
              <CardHeader className="space-y-2 pt-8 text-center">
                <CardTitle className="text-2xl">{tier.name}</CardTitle>
                <p className="text-muted-foreground text-sm text-balance">{tier.description}</p>
              </CardHeader>
              <CardContent className="flex flex-1 flex-col space-y-6">
                <div className="flex items-baseline justify-center">
                  <span className="text-4xl font-bold">{trFmt.format(tier.price)}</span>
                  <span className="text-muted-foreground text-sm">/ay</span>
                </div>
                <div className="space-y-2">
                  {tier.features.map((feature) => (
                    <div key={feature} className="flex items-center gap-2">
                      <div className="bg-muted rounded-full p-1">
                        <Check className="size-3.5" />
                      </div>
                      <span className="text-sm">{feature}</span>
                    </div>
                  ))}
                </div>
              </CardContent>
              <CardFooter>
                {tier.isCurrent ? (
                  <Button className="w-full" size="lg" variant="outline" disabled>
                    Mevcut plan
                  </Button>
                ) : !canManage ? (
                  <Button className="w-full" size="lg" variant="outline" disabled>
                    Sahip yetkisi gerekli
                  </Button>
                ) : tier.id === "pro" ? (
                  <form action={startCheckoutAction} className="w-full">
                    <input type="hidden" name="plan" value="pro" />
                    <Button type="submit" className="w-full" size="lg">
                      <Crown className="size-4" />
                      {shopierActive ? "Pro'ya geç" : "Pro'ya geç (Test)"}
                    </Button>
                  </form>
                ) : (
                  <form action={downgradeToFreeAction} className="w-full">
                    <Button type="submit" className="w-full" size="lg" variant="outline">
                      Ücretsiz'e dön
                    </Button>
                  </form>
                )}
              </CardFooter>
            </Card>
          ))}
        </div>
      </section>

      <section className="space-y-3">
        <div className="flex items-center justify-between">
          <h2 className="text-lg font-semibold tracking-tight">Ekosistem paketleri</h2>
          <Badge variant="outline" className="text-xs">
            <Clock className="size-3" />
            Yakında
          </Badge>
        </div>
        <p className="text-muted-foreground text-sm">
          Sektörel modüller İşletmem'in üzerine eklenecek. Aynı hesabınla farklı şirketleri tek
          panelden yöneteceksin.
        </p>

        <div className="grid gap-6 lg:grid-cols-2">
          {ECOSYSTEM_TIERS.map((t) => (
            <Card key={t.id} className="flex flex-col bg-muted/30">
              <CardHeader>
                <div className="mb-2 flex items-center justify-between">
                  <div className="bg-background flex size-10 items-center justify-center rounded-md border">
                    <t.Icon className="size-5" />
                  </div>
                  <Badge variant="outline" className="text-xs">
                    Yakında
                  </Badge>
                </div>
                <CardTitle className="text-xl">{t.name}</CardTitle>
                <p className="text-muted-foreground text-sm">{t.description}</p>
              </CardHeader>
              <CardContent className="flex flex-1 flex-col">
                <div className="space-y-2">
                  {t.features.map((feature) => (
                    <div key={feature} className="flex items-center gap-2">
                      <div className="bg-background rounded-full p-1">
                        <Check className="size-3.5 text-muted-foreground" />
                      </div>
                      <span className="text-muted-foreground text-sm">{feature}</span>
                    </div>
                  ))}
                </div>
              </CardContent>
              <CardFooter>
                <Button className="w-full" size="lg" variant="outline" disabled>
                  Geliştirme aşamasında
                </Button>
              </CardFooter>
            </Card>
          ))}
        </div>
      </section>

      {!shopierActive && (
        <Card className="bg-muted/20">
          <CardContent className="text-muted-foreground py-4 text-xs">
            <p>
              <span className="text-foreground font-medium">Test modu:</span> Pro plan şu anda mock
              ödeme akışıyla çalışır. Shopier entegrasyonu aktif edilince gerçek tahsilat başlayacak.
            </p>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
