"use client";

import { Check, CheckCircle2, Clock3, Copy, CreditCard, RefreshCw, ShieldCheck, Sparkles, X } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Field, FieldError, FieldGroup } from "@/components/ui/field";
import { Skeleton } from "@/components/ui/skeleton";
import { Spinner } from "@/components/ui/spinner";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { FormErrorAlert, TextField } from "@/components/app/form-fields";
import { cn } from "@/lib/utils";
import { useSubscription } from "./useSubscription";

const CORE_ROWS = [
  ["Unlimited staff", "unlimited"], ["Unlimited purchase orders", "unlimited"], ["Buyer, factory, inquiry & costing", "core"],
  ["PO, production, inspection & shipment", "core"], ["Dashboard, worklist, documents & reports", "core"],
  ["Mailbox", "mailbox"], ["AI assistant", "ai_assistant"], ["Payment & invoicing", "payment_invoicing"],
  ["Custom TNA & approval templates", "custom_tna_templates"], ["Buyer portal · unlimited users", "buyer_portal"], ["Factory portal · unlimited users", "factory_portal"],
];

function taka(value) { return `৳${Number(value || 0).toLocaleString("en-BD", { maximumFractionDigits: 0 })}`; }
function included(plan, key) { return ["unlimited", "core"].includes(key) || Boolean(plan.entitlements?.[key]); }

export function SubscriptionPage({ compact = false }) {
  const subscription = useSubscription();
  if (subscription.loading) return <SubscriptionSkeleton />;
  if (subscription.error) return <LoadError retry={() => subscription.load().catch(() => {})} />;
  if (subscription.data.status === "active" && compact) return null;

  return <div className={cn("mx-auto grid w-full max-w-7xl gap-8", compact ? "px-4 pb-16 sm:px-8" : "px-4 py-8 md:px-6 lg:px-8")}>
    <header className="mx-auto grid max-w-3xl gap-3 text-center">
      <Badge variant="secondary" className="mx-auto"><ShieldCheck /> Manual bKash verification</Badge>
      <h1 className="text-3xl font-semibold tracking-tight sm:text-4xl">{subscription.data.status === "active" ? "Manage your subscription" : "Choose how your team will work"}</h1>
      <p className="text-muted-foreground">Every plan includes unlimited staff and purchase orders. Choose monthly or save with yearly billing; upgrade whenever your operation needs more.</p>
    </header>

    {subscription.pendingPayment
      ? <PendingReview payment={subscription.pendingPayment} onRefresh={subscription.checkApproval} />
      : <PlanAndPayment subscription={subscription} />}

    <Comparison plans={subscription.data.plans} />
  </div>;
}

function PlanAndPayment({ subscription }) {
  const { data, form, selectedPlan } = subscription;
  const cycle = form.watch("billingCycle");
  return <>
    <div className="flex justify-center">
      <ToggleGroup type="single" variant="outline" value={cycle === "pilot" ? "monthly" : cycle} onValueChange={(value) => value && form.setValue("billingCycle", value)} aria-label="Billing cycle">
        <ToggleGroupItem value="monthly">Monthly</ToggleGroupItem>
        <ToggleGroupItem value="yearly">Yearly <Badge variant="secondary" className="ml-1">Save annually</Badge></ToggleGroupItem>
      </ToggleGroup>
    </div>
    <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
      {data.plans.map((plan) => <PlanCard key={plan.id} plan={plan} cycle={cycle} selected={selectedPlan?.id === plan.id} onChoose={() => subscription.choosePlan(plan)} />)}
    </div>
    <PaymentCard subscription={subscription} />
  </>;
}

function PlanCard({ plan, cycle, selected, onChoose }) {
  const price = plan.isOneTime ? plan.monthlyPrice : cycle === "yearly" ? plan.yearlyPrice : plan.monthlyPrice;
  const suffix = plan.isOneTime ? "30 days" : cycle === "yearly" ? "year" : "month";
  return <Card className={cn("relative py-0 transition-colors", selected && "border-primary ring-2 ring-primary/15")}>
    {plan.isRecommended && <Badge className="absolute -top-3 left-4"><Sparkles /> Recommended</Badge>}
    <CardHeader className="gap-3 p-5 pb-3">
      <div><CardTitle>{plan.name}</CardTitle><CardDescription className="mt-1 min-h-10">{plan.tagline}</CardDescription></div>
      <div className="flex flex-wrap items-baseline gap-2">
        {plan.regularPrice && <del className="text-sm text-muted-foreground">{taka(plan.regularPrice)}</del>}
        <span className="text-3xl font-semibold tracking-tight">{taka(price)}</span><span className="text-sm text-muted-foreground">/ {suffix}</span>
      </div>
      {!plan.isOneTime && cycle === "yearly" && <p className="text-xs text-muted-foreground">Equivalent to {taka(plan.yearlyPrice / 12)}/month, billed yearly.</p>}
    </CardHeader>
    <CardContent className="grid gap-4 p-5 pt-0">
      <ul className="grid gap-2 text-sm">
        <li className="flex gap-2"><Check className="mt-0.5 size-4 shrink-0 text-success" /> Unlimited staff & POs</li>
        {Object.entries(plan.entitlements || {}).filter(([, yes]) => yes).slice(0, 3).map(([key]) => <li key={key} className="flex gap-2"><Check className="mt-0.5 size-4 shrink-0 text-success" /> {labelFeature(key)}</li>)}
      </ul>
      <Button type="button" variant={selected ? "default" : "outline"} onClick={onChoose} aria-pressed={selected}>{selected ? <CheckCircle2 /> : <CreditCard />}{selected ? "Selected" : `Choose ${plan.name}`}</Button>
    </CardContent>
  </Card>;
}

function PaymentCard({ subscription }) {
  const { data, form, selectedPlan } = subscription;
  const cycle = form.watch("billingCycle");
  if (!selectedPlan) return null;
  const effectiveCycle = selectedPlan.isOneTime ? "pilot" : cycle;
  const amount = selectedPlan.isOneTime ? selectedPlan.monthlyPrice : effectiveCycle === "yearly" ? selectedPlan.yearlyPrice : selectedPlan.monthlyPrice;
  const copyNumber = async () => { await navigator.clipboard.writeText(data.settings.bkash_number); };

  return <Card className="mx-auto w-full max-w-3xl py-0">
    <CardHeader className="border-b p-5 sm:p-6">
      <CardTitle>Pay with bKash</CardTitle>
      <CardDescription>Send the exact amount first, then submit the sender number and TrxID for manual verification.</CardDescription>
    </CardHeader>
    <CardContent className="grid gap-6 p-5 sm:p-6">
      <div className="grid gap-3 rounded-xl border bg-muted/30 p-4 sm:grid-cols-3">
        <div><p className="text-xs text-muted-foreground">Amount</p><p className="font-semibold">{taka(amount)}</p></div>
        <div><p className="text-xs text-muted-foreground">bKash {data.settings.bkash_account_type}</p><p className="font-semibold tabular-nums">{data.settings.bkash_number}</p></div>
        <Button type="button" variant="outline" size="sm" className="sm:self-center" onClick={copyNumber}><Copy /> Copy number</Button>
      </div>
      <p className="text-sm text-muted-foreground">{data.settings.payment_instructions}</p>
      <form onSubmit={(event) => { form.setValue("billingCycle", effectiveCycle); subscription.submit(event); }} noValidate className="grid gap-5">
        <FormErrorAlert form={form} />
        <FieldGroup className="grid gap-5 sm:grid-cols-2">
          <TextField control={form.control} name="senderNumber" label="bKash sender number" description="The mobile number the payment was sent from." inputProps={{ inputMode: "tel", placeholder: "01XXXXXXXXX" }} />
          <TextField control={form.control} name="transactionId" label="Transaction ID (TrxID)" description="Enter it exactly as shown in the bKash confirmation." inputProps={{ autoCapitalize: "characters", placeholder: "e.g. A1B2C3D4" }} />
        </FieldGroup>
        <div className="flex flex-col gap-3 border-t pt-5 sm:flex-row sm:items-center sm:justify-between">
          <p className="text-sm text-muted-foreground">Submitting does not activate access immediately. An administrator verifies the payment first.</p>
          <Button type="submit" size="lg" disabled={form.formState.isSubmitting || !data.canSubmit}>{form.formState.isSubmitting ? <Spinner /> : <ShieldCheck />} Submit for approval</Button>
        </div>
        {!data.canSubmit && <Field><FieldError>Only the organization owner can submit a subscription payment.</FieldError></Field>}
      </form>
    </CardContent>
  </Card>;
}

function PendingReview({ payment, onRefresh }) {
  return <Card className="mx-auto w-full max-w-3xl py-0">
    <CardContent className="grid gap-6 p-6 text-center sm:p-8">
      <span className="mx-auto grid size-12 place-items-center rounded-full bg-warning/10 text-warning"><Clock3 /></span>
      <div className="grid gap-2"><h2 className="text-xl font-semibold">Payment awaiting approval</h2><p className="text-sm text-muted-foreground">We received {taka(payment.amount)} for {payment.planName} ({payment.billingCycle}). We’ll email the owner after verification.</p></div>
      <div className="mx-auto grid w-full max-w-md grid-cols-2 gap-3 rounded-xl border bg-muted/30 p-4 text-left text-sm">
        <div><span className="text-muted-foreground">Sender</span><p className="font-medium tabular-nums">{payment.senderNumber}</p></div>
        <div><span className="text-muted-foreground">TrxID</span><p className="font-medium tabular-nums">{payment.transactionId}</p></div>
      </div>
      <Button variant="outline" className="mx-auto" onClick={onRefresh}><RefreshCw /> Check approval status</Button>
    </CardContent>
  </Card>;
}

function Comparison({ plans }) {
  return <section className="grid gap-4">
    <div><h2 className="text-xl font-semibold">Compare every capability</h2><p className="text-sm text-muted-foreground">A clear view of what is available and what the software prevents on each plan.</p></div>
    <Card className="overflow-hidden py-0"><div className="overflow-x-auto"><Table>
      <TableHeader><TableRow><TableHead className="min-w-64">Capability</TableHead>{plans.map((plan) => <TableHead key={plan.id} className="min-w-36 text-center">{plan.name}</TableHead>)}</TableRow></TableHeader>
      <TableBody>{CORE_ROWS.map(([label, key]) => <TableRow key={label}><TableCell className="font-medium">{label}</TableCell>{plans.map((plan) => <TableCell key={plan.id} className="text-center">{included(plan, key) ? <Check className="mx-auto size-4 text-success" aria-label="Included" /> : <X className="mx-auto size-4 text-muted-foreground/50" aria-label="Not included" />}</TableCell>)}</TableRow>)}</TableBody>
    </Table></div></Card>
  </section>;
}

function labelFeature(key) { return ({ mailbox: "Mailbox", ai_assistant: "AI assistant", buyer_portal: "Buyer portal", factory_portal: "Factory portal", custom_tna_templates: "Custom TNA templates", payment_invoicing: "Payment & invoicing" })[key] || key; }
function SubscriptionSkeleton() { return <div className="mx-auto grid w-full max-w-7xl gap-6 px-4 py-8"><Skeleton className="mx-auto h-10 w-96 max-w-full" /><div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">{Array.from({ length: 4 }).map((_, i) => <Skeleton key={i} className="h-72 rounded-xl" />)}</div><Skeleton className="mx-auto h-72 w-full max-w-3xl rounded-xl" /></div>; }
function LoadError({ retry }) { return <div className="mx-auto grid max-w-md place-items-center gap-4 px-4 py-16 text-center"><h1 className="text-xl font-semibold">Subscription details could not be loaded</h1><p className="text-sm text-muted-foreground">Your account is safe. Check the connection and try again.</p><Button onClick={retry}><RefreshCw /> Try again</Button></div>; }
