import type { PurchaseContext } from "@/types";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { Switch } from "@/components/ui/switch";
import { servers, players, products } from "@/features/_mock/data";
import { SUBSCRIPTION_PLANS, SUBSCRIPTION } from "@/config/subscription";

export function CheckoutItemDetails({ ctx }: { ctx: PurchaseContext }) {
  return (
    <div className="rounded-xl border border-border bg-card p-4">
      <h3 className="font-semibold">Item</h3>
      <div className="mt-3 flex items-start gap-3">
        <div className="grid h-14 w-14 place-items-center rounded-md bg-surface-elevated text-2xl">
          {ctx.purchaseType === "subscription" ? "🌙" : ctx.purchaseType === "balance" ? "💰" : ctx.purchaseType === "marketplace" ? "🛒" : "🎁"}
        </div>
        <div className="flex-1 min-w-0">
          <div className="font-medium">{ctx.itemName}</div>
          <div className="mt-1 flex flex-wrap items-center gap-1.5">
            <Badge variant="outline" className="capitalize">{ctx.purchaseType.replace("_", " ")}</Badge>
            {ctx.duration && <Badge variant="outline">{ctx.duration}</Badge>}
          </div>
        </div>
        <div className="font-mono font-semibold">${ctx.price.toFixed(2)}</div>
      </div>
    </div>
  );
}

export function CheckoutServerSelector({ value, onChange }: { value?: string; onChange: (v: string) => void }) {
  return (
    <div>
      <Label>Server</Label>
      <Select value={value ?? "all"} onValueChange={onChange}>
        <SelectTrigger><SelectValue /></SelectTrigger>
        <SelectContent>
          <SelectItem value="all">All servers</SelectItem>
          {servers.map((s) => <SelectItem key={s.id} value={s.id}>{s.name}</SelectItem>)}
        </SelectContent>
      </Select>
    </div>
  );
}

export function CheckoutDurationSelector({ options, value, onChange }: { options: string[]; value?: string; onChange: (v: string) => void }) {
  if (options.length <= 1) return null;
  return (
    <div>
      <Label>Duration</Label>
      <Select value={value ?? options[0]} onValueChange={onChange}>
        <SelectTrigger><SelectValue /></SelectTrigger>
        <SelectContent>{options.map((o) => <SelectItem key={o} value={o}>{o}</SelectItem>)}</SelectContent>
      </Select>
    </div>
  );
}

export function CheckoutRecipient({ enabled, onToggle, value, onChange }: { enabled: boolean; onToggle: (v: boolean) => void; value?: string; onChange: (v: string) => void }) {
  return (
    <div className="space-y-2">
      <label className="flex items-center justify-between rounded-md border border-border p-2 text-sm">
        <span>Gift to another player</span>
        <Switch checked={enabled} onCheckedChange={onToggle} />
      </label>
      {enabled && (
        <Select value={value ?? ""} onValueChange={onChange}>
          <SelectTrigger><SelectValue placeholder="Select player" /></SelectTrigger>
          <SelectContent>{players.slice(0, 8).map((p) => <SelectItem key={p.id} value={p.id}>{p.name}</SelectItem>)}</SelectContent>
        </Select>
      )}
    </div>
  );
}

export function CheckoutPaymentMethod({ value, onChange, balance }: { value: string; onChange: (v: string) => void; balance: number }) {
  return (
    <div className="space-y-2">
      <label className={`flex cursor-pointer items-center gap-2 rounded-md border p-3 text-sm ${value === "balance" ? "border-primary" : "border-border"}`}>
        <input type="radio" name="pm" checked={value === "balance"} onChange={() => onChange("balance")} /> Balance (${balance.toFixed(2)} available)
      </label>
      <label className={`flex cursor-pointer items-center gap-2 rounded-md border p-3 text-sm ${value === "card" ? "border-primary" : "border-border"}`}>
        <input type="radio" name="pm" checked={value === "card"} onChange={() => onChange("card")} /> Card / PayPal
      </label>
    </div>
  );
}

export function CheckoutTerms({ checked, onChange }: { checked: boolean; onChange: (v: boolean) => void }) {
  return (
    <label className="flex items-start gap-2 text-xs text-muted-foreground">
      <Checkbox checked={checked} onCheckedChange={(v) => onChange(v === true)} className="mt-0.5" /> I agree to the terms of service and refund policy.
    </label>
  );
}

export function SubscriptionPlanSummary({ planId, autoRenew, onAutoRenew }: { planId?: string; autoRenew: boolean; onAutoRenew: (v: boolean) => void }) {
  const plan = SUBSCRIPTION_PLANS.find((p) => p.id === planId) ?? SUBSCRIPTION_PLANS[0];
  return (
    <div className="rounded-xl border border-border bg-card p-4 space-y-3">
      <h3 className="font-semibold">{SUBSCRIPTION.displayName}</h3>
      <div className="flex items-center justify-between text-sm">
        <span className="text-muted-foreground">Plan</span><span>{plan.label}{plan.lifetime ? " · Lifetime" : ""}</span>
      </div>
      <div className="flex items-center justify-between text-sm">
        <span className="text-muted-foreground">Renewal</span>
        <span>{plan.lifetime ? "One-time purchase" : `Renews every ${plan.label.toLowerCase()}`}</span>
      </div>
      {!plan.lifetime && (
        <label className="flex items-center justify-between rounded-md border border-border p-2 text-sm">
          <span>Auto-renewal</span><Switch checked={autoRenew} onCheckedChange={onAutoRenew} />
        </label>
      )}
      <p className="text-xs text-muted-foreground">You can cancel auto-renewal any time from your account.</p>
    </div>
  );
}

export function PrivilegeDetails({ ctx }: { ctx: PurchaseContext }) {
  const p = products.find((x) => x.id === ctx.itemId);
  return (
    <div className="rounded-xl border border-border bg-card p-4 space-y-2 text-sm">
      <h3 className="font-semibold">Privilege benefits</h3>
      <ul className="text-muted-foreground list-disc pl-5 space-y-1">
        <li>Priority slot on selected server</li>
        <li>Custom chat color and reserved slot</li>
        <li>+5% experience while playing</li>
      </ul>
      {p && <div className="text-xs text-muted-foreground">Applies to: {p.duration}</div>}
    </div>
  );
}

export function BalanceTopUpPreview({ ctx, currentBalance }: { ctx: PurchaseContext; currentBalance: number }) {
  const bonus = ctx.price >= 25 ? +(ctx.price * 0.05).toFixed(2) : 0;
  return (
    <div className="rounded-xl border border-border bg-card p-4 space-y-2 text-sm">
      <h3 className="font-semibold">Balance top-up</h3>
      <div className="flex justify-between"><span className="text-muted-foreground">Amount</span><span className="font-mono">${ctx.price.toFixed(2)}</span></div>
      {bonus > 0 && <div className="flex justify-between text-success"><span>Bonus (5%)</span><span className="font-mono">+${bonus.toFixed(2)}</span></div>}
      <div className="border-t border-border pt-2 flex justify-between font-semibold"><span>New balance</span><span className="font-mono text-secondary">${(currentBalance + ctx.price + bonus).toFixed(2)}</span></div>
    </div>
  );
}

export function MarketplaceDetails({ ctx, fee }: { ctx: PurchaseContext; fee: number }) {
  return (
    <div className="rounded-xl border border-border bg-card p-4 space-y-2 text-sm">
      <h3 className="font-semibold">Marketplace</h3>
      <div className="flex justify-between"><span className="text-muted-foreground">Seller</span><span>{(ctx.metadata?.sellerName as string) ?? "—"}</span></div>
      <div className="flex justify-between"><span className="text-muted-foreground">Quantity</span><span>{ctx.quantity ?? 1}</span></div>
      <div className="flex justify-between"><span className="text-muted-foreground">Marketplace fee (5%)</span><span className="font-mono">${fee.toFixed(2)}</span></div>
      <p className="text-xs text-muted-foreground">Trade restrictions may apply per Steam policy.</p>
    </div>
  );
}

export function ProductOptions({ ctx, onQuantity, quantity }: { ctx: PurchaseContext; quantity: number; onQuantity: (n: number) => void }) {
  const p = products.find((x) => x.id === ctx.itemId);
  if (!p) return null;
  return (
    <div className="rounded-xl border border-border bg-card p-4 space-y-3">
      <h3 className="font-semibold">Options</h3>
      <div className="flex items-center gap-2">
        <Label className="w-24">Quantity</Label>
        <Input type="number" min={1} max={99} value={quantity} onChange={(e) => onQuantity(Math.max(1, Number(e.target.value) || 1))} className="w-24" />
      </div>
    </div>
  );
}