import { createFileRoute, Link } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { PageHeader, EmptyState } from "@/components/common/PageHeader";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { toast } from "sonner";
import type { Subscription, SubscriptionSettings } from "@/types";
import { subscriptionsService } from "@/services/api/subscriptions";
import { SUBSCRIPTION, SUBSCRIPTION_PLANS } from "@/config/subscription";
import { SubscriptionStatusPill, SubscriptionExpirationNotice, SubscriptionSettingsPreview } from "@/features/subscription/components";
import { useAuthStore } from "@/store/auth";

export const Route = createFileRoute("/_public/account/subscription")({
  head: () => ({ meta: [{ title: `${SUBSCRIPTION.shortName} — Account` }] }),
  component: AccountSubscriptionPage,
});

function daysBetween(a: string, b: string) {
  return Math.max(0, Math.round((new Date(a).getTime() - new Date(b).getTime()) / 86_400_000));
}

function AccountSubscriptionPage() {
  const user = useAuthStore((s) => s.user);
  const [sub, setSub] = useState<Subscription | null>(null);
  const [settings, setSettings] = useState<SubscriptionSettings>(SUBSCRIPTION.defaultSettings);

  useEffect(() => {
    subscriptionsService.me().then(setSub);
    subscriptionsService.settings().then(setSettings);
  }, []);

  async function save() {
    await subscriptionsService.saveSettings(settings);
    toast.success("Settings saved");
  }

  async function cancel() {
    const next = await subscriptionsService.cancelAutoRenew();
    setSub(next);
    toast.success("Auto-renewal disabled");
  }

  if (!sub) {
    return (
      <div className="space-y-4">
        <PageHeader title={SUBSCRIPTION.displayName} description="You don’t have an active subscription." />
        <EmptyState title="No subscription" hint="Choose a plan to unlock multipliers, cosmetics and marketplace perks." />
        <div className="flex justify-center"><Button asChild className="gradient-primary text-primary-foreground"><Link to="/subscription">See plans</Link></Button></div>
      </div>
    );
  }

  const plan = SUBSCRIPTION_PLANS.find((p) => p.id === sub.planId);
  const remaining = daysBetween(sub.expiresAt, new Date().toISOString());

  return (
    <div className="space-y-6">
      <PageHeader title={SUBSCRIPTION.displayName} description="Manage your subscription and cosmetics." />

      <div className="rounded-xl border border-border bg-card p-5">
        <div className="flex flex-wrap items-center gap-3">
          <div>
            <div className="font-display text-xl font-semibold">{plan?.label ?? sub.planId}</div>
            <div className="text-xs text-muted-foreground">Started {sub.startsAt}</div>
          </div>
          <SubscriptionStatusPill status={sub.status} />
          <div className="ml-auto flex gap-2">
            {sub.autoRenew && !plan?.lifetime && <Button variant="outline" onClick={cancel}>Cancel auto-renew</Button>}
            <Button asChild className="gradient-primary text-primary-foreground"><Link to="/subscription">Change plan</Link></Button>
          </div>
        </div>
        <div className="mt-3"><SubscriptionExpirationNotice expiresAt={sub.expiresAt} remainingDays={remaining} /></div>
      </div>

      <div className="grid gap-6 lg:grid-cols-[1fr_360px]">
        <div className="space-y-4">
          <div className="rounded-xl border border-border bg-card p-4">
            <h3 className="font-semibold">Badge visibility</h3>
            <div className="mt-3 grid gap-2 sm:grid-cols-2">
              {([
                ["badgeVisibleProfile", "Profile"],
                ["badgeVisibleChat", "Chat"],
                ["badgeVisibleRankings", "Rankings"],
                ["badgeVisibleScoreboard", "Scoreboard"],
              ] as const).map(([k, label]) => (
                <label key={k} className="flex items-center justify-between rounded-md border border-border p-2 text-sm">
                  <span>{label}</span>
                  <Switch checked={settings[k]} onCheckedChange={(v) => setSettings((s) => ({ ...s, [k]: v }))} />
                </label>
              ))}
            </div>
          </div>

          <div className="rounded-xl border border-border bg-card p-4 space-y-3">
            <h3 className="font-semibold">Colors</h3>
            <div className="grid gap-3 sm:grid-cols-2">
              {([
                ["nicknameColor", "Nickname color"],
                ["chatAccent", "Chat accent"],
                ["tagColor", "Tag color"],
                ["profileAccent", "Profile accent"],
              ] as const).map(([k, label]) => (
                <div key={k}>
                  <Label>{label}</Label>
                  <div className="mt-1 flex gap-2">
                    <Input type="color" value={settings[k]} onChange={(e) => setSettings((s) => ({ ...s, [k]: e.target.value }))} className="h-9 w-14 p-1" />
                    <Input value={settings[k]} onChange={(e) => setSettings((s) => ({ ...s, [k]: e.target.value }))} className="flex-1 font-mono" />
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="rounded-xl border border-border bg-card p-4">
            <h3 className="font-semibold">Notifications</h3>
            <div className="mt-3 space-y-2">
              {([
                ["notifyDailyRewards", "Daily rewards reminder"],
                ["notifyMarketplace", "Marketplace price alerts"],
                ["notifyRenewal", "Renewal reminders"],
              ] as const).map(([k, label]) => (
                <label key={k} className="flex items-center justify-between rounded-md border border-border p-2 text-sm">
                  <span>{label}</span>
                  <Switch checked={settings[k]} onCheckedChange={(v) => setSettings((s) => ({ ...s, [k]: v }))} />
                </label>
              ))}
            </div>
          </div>

          <div className="flex justify-end"><Button onClick={save} className="gradient-primary text-primary-foreground">Save settings</Button></div>
        </div>

        <div className="space-y-3">
          <h3 className="font-semibold">Preview</h3>
          <SubscriptionSettingsPreview settings={settings} name={user?.name ?? "you"} />
        </div>
      </div>

      <div className="rounded-xl border border-border bg-card p-4">
        <h3 className="font-semibold">Payment history</h3>
        <table className="mt-3 w-full text-sm">
          <thead className="bg-surface text-left text-xs uppercase text-muted-foreground"><tr><th className="px-3 py-2">Date</th><th className="px-3 py-2">Amount</th><th className="px-3 py-2">Status</th></tr></thead>
          <tbody className="divide-y divide-border/40">
            {sub.paymentHistory.map((p) => (
              <tr key={p.id}><td className="px-3 py-2">{p.date}</td><td className="px-3 py-2 font-mono">${p.amount.toFixed(2)}</td><td className="px-3 py-2 capitalize">{p.status}</td></tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}