"use client";

import { useState, useTransition } from "react";
import { toast } from "sonner";
import { Crown, Check, CircleNotch, Star, Lightning, X, Envelope, Tag } from "@/lib/icons";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import {
  startCheckoutAction,
  getPayTRTokenAction,
  requestEnterpriseInquiryAction,
} from "@/lib/appwrite/subscription-actions";
import { PLAN_CATALOG, PLAN_RANK, planPriceDisplay, planPrice, validateDiscountCode } from "@/lib/appwrite/subscription-types";
import type { TenantPlan, PlanPeriod } from "@/lib/appwrite/schema";

const PLAN_ICONS: Record<string, React.ReactNode> = {
  starter:    <Lightning className="h-5 w-5" />,
  pro:        <Star className="h-5 w-5" />,
  enterprise: <Crown className="h-5 w-5" />,
};

function calcProration(
  currentPlan: TenantPlan,
  currentPeriod: PlanPeriod,
  planExpiresAt: string | null,
  newPlanPrice: number,
): number {
  if (!planExpiresAt || currentPlan === "free") return newPlanPrice;
  const currentEntry = PLAN_CATALOG[currentPlan as Exclude<TenantPlan, "free">];
  if (!currentEntry) return newPlanPrice;
  const periodDays = currentPeriod === "yearly" ? 365 : 30;
  const msRemaining = new Date(planExpiresAt).getTime() - Date.now();
  const daysRemaining = Math.max(0, msRemaining / (1000 * 60 * 60 * 24));
  const unusedFraction = Math.min(1, daysRemaining / periodDays);
  const credit = planPrice(currentEntry, currentPeriod) * unusedFraction;
  return Math.max(1, Math.round(newPlanPrice - credit));
}

export function UpgradeSection({
  currentPlan,
  currentPeriod,
  planExpiresAt,
  paytrEnabled,
}: {
  currentPlan: TenantPlan;
  currentPeriod?: PlanPeriod | null;
  planExpiresAt?: string | null;
  paytrEnabled?: boolean;
}) {
  const [period, setPeriod] = useState<PlanPeriod>(currentPeriod ?? "monthly");
  const [paytrToken, setPaytrToken] = useState<string | null>(null);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [enterpriseDialogOpen, setEnterpriseDialogOpen] = useState(false);
  const [loadingPlan, setLoadingPlan] = useState<string | null>(null);
  const [discountCode, setDiscountCode] = useState("");
  const [discountApplied, setDiscountApplied] = useState<number | null>(null);
  const [isPending, startTransition] = useTransition();
  const [enterpriseForm, setEnterpriseForm] = useState({
    teamSize: "",
    listingCount: "",
    needsCustomDev: "",
    notes: "",
  });

  const plans = Object.values(PLAN_CATALOG);
  const currentRank = PLAN_RANK[currentPlan];

  function applyDiscount() {
    if (!discountCode.trim()) return;
    const fraction = validateDiscountCode(discountCode);
    if (fraction === null) {
      toast.error("Geçersiz indirim kodu.");
      setDiscountApplied(null);
      return;
    }
    setDiscountApplied(fraction);
    toast.success(`İndirim kodu uygulandı: %${Math.round(fraction * 100)} indirim`);
  }

  function getDisplayPrice(plan: typeof plans[0]): number {
    let base = planPriceDisplay(plan, period);
    if (discountApplied !== null) base = Math.round(base * (1 - discountApplied));
    return base;
  }

  function getProrationAmount(planId: string): number | null {
    if (currentPlan === "free" || !planExpiresAt) return null;
    const entry = PLAN_CATALOG[planId as Exclude<TenantPlan, "free">];
    if (!entry) return null;
    let base = planPrice(entry, period);
    if (discountApplied !== null) base = Math.max(1, Math.round(base * (1 - discountApplied)));
    const prorated = calcProration(currentPlan, currentPeriod ?? "monthly", planExpiresAt, base);
    return prorated < base ? prorated : null;
  }

  function handleCheckout(planId: string) {
    if (paytrEnabled) {
      setLoadingPlan(planId);
      startTransition(async () => {
        try {
          const fd = new FormData();
          fd.set("plan", planId);
          fd.set("period", period);
          if (discountApplied !== null) fd.set("discountCode", discountCode.trim().toUpperCase());
          const token = await getPayTRTokenAction(fd);
          setPaytrToken(token);
          setDialogOpen(true);
        } catch (e) {
          toast.error(e instanceof Error ? e.message : "Ödeme başlatılamadı.");
        } finally {
          setLoadingPlan(null);
        }
      });
    } else {
      setLoadingPlan(planId);
      startTransition(async () => {
        try {
          const fd = new FormData();
          fd.set("plan", planId);
          await startCheckoutAction(fd);
        } catch (e) {
          if (e instanceof Error && e.message.includes("NEXT_REDIRECT")) throw e;
          toast.error("Ödeme başlatılamadı.");
        } finally {
          setLoadingPlan(null);
        }
      });
    }
  }

  function handleEnterpriseInquiry() {
    if (!enterpriseForm.teamSize || !enterpriseForm.listingCount || !enterpriseForm.needsCustomDev) {
      toast.error("Lütfen tüm zorunlu alanları doldurun.");
      return;
    }
    startTransition(async () => {
      try {
        const fd = new FormData();
        fd.set("teamSize", enterpriseForm.teamSize);
        fd.set("listingCount", enterpriseForm.listingCount);
        fd.set("needsCustomDev", enterpriseForm.needsCustomDev);
        fd.set("notes", enterpriseForm.notes);
        const result = await requestEnterpriseInquiryAction(fd);
        if (result.ok) {
          setEnterpriseDialogOpen(false);
          setEnterpriseForm({ teamSize: "", listingCount: "", needsCustomDev: "", notes: "" });
          toast.success("Talebiniz alındı. Ekibimiz kısa sürede sizinle iletişime geçecek.");
        } else {
          toast.error(result.error ?? "Talep gönderilemedi.");
        }
      } catch (e) {
        toast.error(e instanceof Error ? e.message : "Talep gönderilemedi.");
      }
    });
  }

  return (
    <>
      <div className="space-y-6">
        {/* Başlık + toggle */}
        <div className="flex flex-col items-center gap-4 text-center">
          <div>
            <h2 className="text-xl font-bold tracking-tight">Planınızı seçin</h2>
            <p className="text-muted-foreground text-sm mt-1">
              Dilediğiniz zaman daha üst bir plana geçebilirsiniz.
            </p>
          </div>
          <div className="flex items-center gap-1 rounded-full border bg-muted/40 p-1 text-sm">
            <button
              onClick={() => setPeriod("monthly")}
              className={`rounded-full px-5 py-1.5 font-medium transition-all ${
                period === "monthly"
                  ? "bg-background shadow-sm text-foreground"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              Aylık
            </button>
            <button
              onClick={() => setPeriod("yearly")}
              className={`flex items-center gap-2 rounded-full px-5 py-1.5 font-medium transition-all ${
                period === "yearly"
                  ? "bg-background shadow-sm text-foreground"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              Yıllık
              <Badge variant="secondary" className="text-[11px] px-1.5 py-0 rounded-full">
                2 ay bedava
              </Badge>
            </button>
          </div>

          {/* İndirim kodu */}
          <div className="flex items-center gap-2">
            <div className="relative">
              <Tag className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
              <input
                type="text"
                value={discountCode}
                onChange={(e) => {
                  setDiscountCode(e.target.value.toUpperCase());
                  if (discountApplied !== null) setDiscountApplied(null);
                }}
                onKeyDown={(e) => e.key === "Enter" && applyDiscount()}
                placeholder="İndirim kodu"
                className="h-9 w-40 rounded-lg border bg-background pl-8 pr-3 text-sm outline-none focus:ring-1 focus:ring-primary"
              />
            </div>
            <Button
              variant="outline"
              size="sm"
              onClick={applyDiscount}
              disabled={!discountCode.trim()}
            >
              Uygula
            </Button>
            {discountApplied !== null && (
              <Badge variant="secondary" className="gap-1">
                <Check className="h-3 w-3" />
                %{Math.round(discountApplied * 100)} indirim
              </Badge>
            )}
          </div>
        </div>

        {/* 3 plan kartı */}
        <div className="grid gap-4 sm:grid-cols-3">
          {plans.map((plan) => {
            const isCurrent = currentPlan === plan.id;
            const isLower = PLAN_RANK[plan.id as TenantPlan] < currentRank;
            const isEnterprise = plan.id === "enterprise";
            const displayPrice = getDisplayPrice(plan);
            const prorationAmount = !isCurrent && !isLower ? getProrationAmount(plan.id) : null;
            const isLoading = isPending && loadingPlan === plan.id;

            return (
              <Card
                key={plan.id}
                className={`relative flex flex-col transition-shadow ${
                  plan.highlight
                    ? "border-primary shadow-md ring-1 ring-primary/20"
                    : ""
                } ${isLower ? "opacity-50" : ""}`}
              >
                {plan.highlight && (
                  <div className="absolute -top-3.5 inset-x-0 flex justify-center">
                    <Badge className="rounded-full px-3 text-xs shadow-sm">
                      Popüler
                    </Badge>
                  </div>
                )}

                <CardHeader className="pb-4 pt-6">
                  <div className={`flex items-center gap-2 mb-3 ${plan.highlight ? "text-primary" : ""}`}>
                    {PLAN_ICONS[plan.id]}
                    <span className="font-semibold text-base">{plan.name}</span>
                    {isCurrent && (
                      <Badge variant="outline" className="text-[10px] px-1.5 py-0 h-4 ml-auto">
                        Mevcut
                      </Badge>
                    )}
                  </div>
                  <div className="flex items-end gap-1">
                    <span className="text-4xl font-bold tracking-tight">
                      {displayPrice.toLocaleString("tr-TR")}
                    </span>
                    <span className="text-muted-foreground text-sm mb-1">₺/ay</span>
                    {discountApplied !== null && !isCurrent && !isLower && (
                      <span className="text-muted-foreground text-xs line-through mb-1 ml-1">
                        {planPriceDisplay(plan, period).toLocaleString("tr-TR")}₺
                      </span>
                    )}
                  </div>
                  {period === "yearly" ? (
                    <p className="text-xs text-muted-foreground">
                      {plan.yearly.toLocaleString("tr-TR")} ₺ yıllık faturalandırılır
                    </p>
                  ) : (
                    <p className="text-xs text-muted-foreground">{plan.description}</p>
                  )}
                </CardHeader>

                <CardContent className="flex flex-col flex-1 gap-5">
                  <ul className="space-y-2.5 flex-1">
                    {plan.features.map((f) => (
                      <li key={f} className="flex items-start gap-2 text-sm">
                        <Check className="h-4 w-4 text-primary shrink-0 mt-0.5" />
                        <span>{f}</span>
                      </li>
                    ))}
                  </ul>

                  {isCurrent ? (
                    <Button variant="outline" className="w-full" disabled>
                      Mevcut Planınız
                    </Button>
                  ) : isLower ? (
                    <Button variant="outline" className="w-full" disabled>
                      Plan düşürülemez
                    </Button>
                  ) : isEnterprise ? (
                    <Button
                      className="w-full gap-2"
                      variant="outline"
                      onClick={() => setEnterpriseDialogOpen(true)}
                      disabled={isPending}
                    >
                      <Envelope className="h-4 w-4" />
                      Teklif Al
                    </Button>
                  ) : (
                    <div className="space-y-1.5">
                      <Button
                        className="w-full gap-2"
                        variant={plan.highlight ? "default" : "outline"}
                        disabled={isPending}
                        onClick={() => handleCheckout(plan.id)}
                      >
                        {isLoading ? (
                          <CircleNotch className="h-4 w-4 animate-spin" />
                        ) : (
                          PLAN_ICONS[plan.id]
                        )}
                        {isLoading ? "Yükleniyor..." : `${plan.name}'a Geç`}
                      </Button>
                      {prorationAmount !== null && (
                        <p className="text-center text-[11px] text-muted-foreground">
                          Bugün sadece{" "}
                          <span className="font-medium text-foreground">
                            {prorationAmount.toLocaleString("tr-TR")} ₺
                          </span>{" "}
                          ödersiniz (kalan süre mahsup edilir)
                        </p>
                      )}
                    </div>
                  )}
                </CardContent>
              </Card>
            );
          })}
        </div>

        <p className="text-center text-xs text-muted-foreground">
          Abonelik iptali için{" "}
          <a href="mailto:info@kovakyazilim.com" className="underline hover:text-foreground transition-colors">
            info@kovakyazilim.com
          </a>{" "}
          ile iletişime geçin.
        </p>
      </div>

      {/* PayTR iframe dialog */}
      {paytrEnabled && (
        <Dialog
          open={dialogOpen}
          onOpenChange={(open) => {
            setDialogOpen(open);
            if (!open) setPaytrToken(null);
          }}
        >
          <DialogContent className="sm:max-w-lg p-0 overflow-hidden" showCloseButton={false}>
            <DialogHeader className="flex flex-row items-center justify-between px-4 py-3 border-b">
              <DialogTitle className="text-base">Güvenli Ödeme</DialogTitle>
              <Button
                variant="ghost"
                size="icon"
                className="h-7 w-7 shrink-0"
                onClick={() => setDialogOpen(false)}
              >
                <X className="h-4 w-4" />
              </Button>
            </DialogHeader>
            {paytrToken && (
              <iframe
                src={`https://www.paytr.com/odeme/guvenli/${paytrToken}`}
                className="w-full border-none"
                style={{ height: 560 }}
                allowFullScreen
              />
            )}
          </DialogContent>
        </Dialog>
      )}

      {/* Enterprise inquiry dialog */}
      <Dialog open={enterpriseDialogOpen} onOpenChange={setEnterpriseDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Crown className="h-5 w-5 text-primary" />
              Enterprise Plan Teklifi
            </DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-1">
            <p className="text-sm text-muted-foreground">
              Ekibimiz sizin için özel fiyatlandırma ve kurulum planı hazırlasın. Birkaç soruyu
              yanıtlayın, en kısa sürede size ulaşalım.
            </p>

            {/* Ekip büyüklüğü */}
            <div className="space-y-1.5">
              <label className="text-sm font-medium">
                Ekibinizdeki danışman sayısı <span className="text-destructive">*</span>
              </label>
              <div className="grid grid-cols-4 gap-2">
                {["1-3", "4-10", "11-25", "25+"].map((opt) => (
                  <button
                    key={opt}
                    type="button"
                    onClick={() => setEnterpriseForm((f) => ({ ...f, teamSize: opt }))}
                    className={`rounded-lg border py-2 text-sm font-medium transition-colors ${
                      enterpriseForm.teamSize === opt
                        ? "border-primary bg-primary/10 text-primary"
                        : "hover:border-primary/40"
                    }`}
                  >
                    {opt}
                  </button>
                ))}
              </div>
            </div>

            {/* Ilan sayısı */}
            <div className="space-y-1.5">
              <label className="text-sm font-medium">
                Aktif ilan sayınız <span className="text-destructive">*</span>
              </label>
              <div className="grid grid-cols-4 gap-2">
                {["1-50", "51-200", "201-500", "500+"].map((opt) => (
                  <button
                    key={opt}
                    type="button"
                    onClick={() => setEnterpriseForm((f) => ({ ...f, listingCount: opt }))}
                    className={`rounded-lg border py-2 text-sm font-medium transition-colors ${
                      enterpriseForm.listingCount === opt
                        ? "border-primary bg-primary/10 text-primary"
                        : "hover:border-primary/40"
                    }`}
                  >
                    {opt}
                  </button>
                ))}
              </div>
            </div>

            {/* Özel modül */}
            <div className="space-y-1.5">
              <label className="text-sm font-medium">
                Özel modül / entegrasyon geliştirmesi istiyor musunuz?{" "}
                <span className="text-destructive">*</span>
              </label>
              <div className="grid grid-cols-3 gap-2">
                {[
                  { value: "yes", label: "Evet" },
                  { value: "no", label: "Hayır" },
                  { value: "maybe", label: "Değerlendiriyorum" },
                ].map((opt) => (
                  <button
                    key={opt.value}
                    type="button"
                    onClick={() => setEnterpriseForm((f) => ({ ...f, needsCustomDev: opt.value }))}
                    className={`rounded-lg border py-2 text-sm font-medium transition-colors ${
                      enterpriseForm.needsCustomDev === opt.value
                        ? "border-primary bg-primary/10 text-primary"
                        : "hover:border-primary/40"
                    }`}
                  >
                    {opt.label}
                  </button>
                ))}
              </div>
            </div>

            {/* Notlar */}
            <div className="space-y-1.5">
              <label className="text-sm font-medium">
                Eklemek istediğiniz notlar{" "}
                <span className="text-muted-foreground font-normal">(isteğe bağlı)</span>
              </label>
              <textarea
                rows={3}
                value={enterpriseForm.notes}
                onChange={(e) => setEnterpriseForm((f) => ({ ...f, notes: e.target.value }))}
                placeholder="Özel ihtiyaçlarınızı, entegrasyon beklentilerinizi veya sorularınızı buraya yazabilirsiniz..."
                className="w-full rounded-lg border bg-background px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-primary resize-none"
              />
            </div>

            <div className="flex gap-2 pt-1">
              <Button
                variant="outline"
                className="flex-1"
                onClick={() => setEnterpriseDialogOpen(false)}
                disabled={isPending}
              >
                Vazgeç
              </Button>
              <Button
                className="flex-1 gap-2"
                onClick={handleEnterpriseInquiry}
                disabled={isPending || !enterpriseForm.teamSize || !enterpriseForm.listingCount || !enterpriseForm.needsCustomDev}
              >
                {isPending ? (
                  <CircleNotch className="h-4 w-4 animate-spin" />
                ) : (
                  <Envelope className="h-4 w-4" />
                )}
                Teklif Gönder
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}
