"use client";

import { useRef } from "react";
import { toast } from "sonner";
import { Crown, Check, CircleNotch } from '@/lib/icons';
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { startCheckoutAction, downgradeToFreeAction } from "@/lib/appwrite/subscription-actions";
import { PLAN_CATALOG } from "@/lib/appwrite/subscription-types";
import type { TenantPlan } from "@/lib/appwrite/schema";

export function UpgradeSection({ currentPlan }: { currentPlan: TenantPlan }) {
  const formRef = useRef<HTMLFormElement>(null);

  const pro = PLAN_CATALOG.pro;
  const isPro = currentPlan === "pro";

  async function handleUpgrade(formData: FormData) {
    try {
      await startCheckoutAction(formData);
    } catch (e) {
      if (e instanceof Error && e.message.includes("NEXT_REDIRECT")) throw e;
      toast.error("Ödeme başlatılamadı. Tekrar deneyin.");
    }
  }

  async function handleDowngrade() {
    const fd = new FormData();
    try {
      await downgradeToFreeAction();
    } catch (e) {
      if (e instanceof Error && e.message.includes("NEXT_REDIRECT")) throw e;
      void fd;
      toast.error("İşlem başarısız. Tekrar deneyin.");
    }
  }

  if (isPro) {
    return (
      <Card className="border-primary/30 bg-primary/5">
        <CardHeader>
          <div className="flex items-center gap-2">
            <Crown className="h-5 w-5 text-primary" />
            <CardTitle className="text-base">Pro Plan Aktif</CardTitle>
          </div>
          <CardDescription>
            Tüm özelliklere sınırsız erişiminiz var.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form action={handleDowngrade}>
            <Button type="submit" variant="outline" size="sm" className="text-muted-foreground">
              Ücretsiz plana geç
            </Button>
          </form>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="border-primary/30">
      <CardHeader>
        <div className="flex items-center gap-2">
          <CardTitle className="text-base">{pro.name} Plana Geç</CardTitle>
          <Badge variant="secondary" className="text-xs">Önerilen</Badge>
        </div>
        <CardDescription>{pro.description}</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <ul className="space-y-1.5">
          {pro.features.map((f) => (
            <li key={f} className="flex items-center gap-2 text-sm">
              <Check className="h-3.5 w-3.5 text-primary shrink-0" />
              {f}
            </li>
          ))}
        </ul>

        <div className="flex items-baseline gap-1">
          <span className="text-3xl font-bold">{pro.price.toLocaleString("tr-TR")}</span>
          <span className="text-muted-foreground text-sm">₺ / ay</span>
        </div>

        <form ref={formRef} action={handleUpgrade}>
          <input type="hidden" name="plan" value="pro" />
          <Button type="submit" className="w-full gap-2 cursor-pointer">
            <Crown className="h-4 w-4" />
            Pro&apos;ya Geç
          </Button>
        </form>
      </CardContent>
    </Card>
  );
}
