"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { Avatar, Button, EmptyState, useToast } from "@/components/ui";
import { useSession } from "@/components/session-provider";
import { api, uploadFile } from "@/lib/api-client";
import { LANGUAGES } from "@/lib/constants";
import { formatMoney } from "@/lib/format";

type Me = {
  user: {
    id: string; displayName: string; email: string; handle: string; avatarUrl: string | null; bannerUrl: string | null;
    bio: string | null; language: string; theme: string; country: string; restrictedMode: boolean; parentalLock: boolean;
    parentalPin: string | null; cookieConsent: boolean; emailVerified: boolean;
  };
  channel: { id: string; name: string; handle: string } | null;
  subscriptions: { channelId: string; name: string; handle: string; notify: boolean }[];
  memberships: { id: string; channelName: string; priceCents: number }[];
  payments: { id: string; kind: string; amountCents: number; createdAt: string }[];
  blocked: { id: string; name: string; handle: string }[];
};

export default function SettingsPage() {
  const { user, refresh, setLang, setTheme, theme, lang } = useSession();
  const { toast, toastNode } = useToast();
  const [me, setMe] = useState<Me | null>(null);
  const [passwords, setPasswords] = useState({ currentPassword: "", newPassword: "" });

  useEffect(() => {
    if (!user) return;
    void api<Me>("/api/me").then(setMe).catch((e) => toast(e.message));
  }, [user, toast]);

  if (!user) return <div className="p-6"><EmptyState icon="🔒" title="Sign in to manage your settings" action={<Link href="/login" className="text-sm font-semibold text-brand">Sign in</Link>} /></div>;
  if (!me) return <div className="p-6"><div className="skeleton h-64 w-full rounded-xl" /></div>;

  const patch = async (payload: Record<string, unknown>) => {
    await api("/api/me", { method: "PATCH", json: payload }).catch((e) => toast(e.message));
    await refresh();
    const fresh = await api<Me>("/api/me").catch(() => null);
    if (fresh) setMe(fresh);
    toast("Settings saved");
  };

  return (
    <div className="mx-auto max-w-3xl space-y-6 px-4 py-6">
      <h1 className="text-2xl font-bold">Settings</h1>

      <section className="space-y-4 rounded-xl border border-line p-4">
        <h2 className="text-sm font-bold uppercase tracking-wide text-muted">Profile</h2>
        <div className="flex flex-wrap items-center gap-4">
          <Avatar name={me.user.displayName} src={me.user.avatarUrl} size={72} />
          <label className="cursor-pointer rounded-full bg-surface px-3 py-1.5 text-sm font-medium">
            Change profile picture
            <input type="file" accept="image/*" hidden onChange={async (event) => {
              const file = event.target.files?.[0];
              if (!file) return;
              try {
                const stored = await uploadFile(file, "image", "uploads/avatars");
                await patch({ avatarUrl: stored.url });
              } catch (error) {
                toast(error instanceof Error ? error.message : "Upload failed");
              }
            }} />
          </label>
          <label className="cursor-pointer rounded-full bg-surface px-3 py-1.5 text-sm font-medium">
            Change banner
            <input type="file" accept="image/*" hidden onChange={async (event) => {
              const file = event.target.files?.[0];
              if (!file) return;
              const stored = await uploadFile(file, "image", "uploads/banners").catch((e) => { toast(e.message); return null; });
              if (stored) await patch({ bannerUrl: stored.url });
            }} />
          </label>
        </div>
        <input defaultValue={me.user.displayName} onBlur={(event) => void patch({ displayName: event.target.value })} className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm" />
        <textarea defaultValue={me.user.bio ?? ""} onBlur={(event) => void patch({ bio: event.target.value })} rows={2} placeholder="Bio" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm" />
        <p className="text-xs text-muted">{me.user.email} {me.user.emailVerified ? "✓ verified" : "· not verified"} · @{me.user.handle}</p>
        {!me.user.emailVerified ? (
          <Button size="sm" variant="secondary" onClick={async () => {
            const data = await api<{ verifyUrl: string | null }>("/api/auth/resend-verification", { method: "POST" }).catch(() => null);
            if (data?.verifyUrl) window.location.href = data.verifyUrl;
            else toast("Verification email sent");
          }}>
            Verify email
          </Button>
        ) : null}
      </section>

      <section className="space-y-4 rounded-xl border border-line p-4">
        <h2 className="text-sm font-bold uppercase tracking-wide text-muted">Appearance &amp; language</h2>
        <div className="grid gap-3 sm:grid-cols-2">
          <label className="space-y-1">
            <span className="text-xs font-semibold uppercase text-muted">Theme</span>
            <select value={theme} onChange={(event) => { setTheme(event.target.value as "dark" | "light"); void patch({ theme: event.target.value }); }} className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm">
              <option value="dark">Dark</option>
              <option value="light">Light</option>
            </select>
          </label>
          <label className="space-y-1">
            <span className="text-xs font-semibold uppercase text-muted">Language</span>
            <select value={lang} onChange={(event) => { setLang(event.target.value); void patch({ language: event.target.value }); }} className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm">
              {LANGUAGES.map((language) => (
                <option key={language.code} value={language.code}>{language.label}</option>
              ))}
            </select>
          </label>
          <label className="space-y-1">
            <span className="text-xs font-semibold uppercase text-muted">Country</span>
            <input defaultValue={me.user.country} onBlur={(event) => void patch({ country: event.target.value })} className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm" />
          </label>
        </div>
      </section>

      <section className="space-y-3 rounded-xl border border-line p-4">
        <h2 className="text-sm font-bold uppercase tracking-wide text-muted">Privacy &amp; parental controls</h2>
        <label className="flex items-center justify-between text-sm">
          <span>Restricted mode (hide mature content)</span>
          <input type="checkbox" checked={me.user.restrictedMode} onChange={(event) => void patch({ restrictedMode: event.target.checked })} />
        </label>
        <label className="flex items-center justify-between text-sm">
          <span>Parental lock (PIN required for uploads &amp; live)</span>
          <input type="checkbox" checked={me.user.parentalLock} onChange={(event) => void patch({ parentalLock: event.target.checked })} />
        </label>
        <input defaultValue={me.user.parentalPin ?? ""} onBlur={(event) => void patch({ parentalPin: event.target.value })} placeholder="Parental PIN" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm" />
        <label className="flex items-center justify-between text-sm">
          <span>Allow cookies for personalisation</span>
          <input type="checkbox" checked={me.user.cookieConsent} onChange={(event) => void patch({ cookieConsent: event.target.checked })} />
        </label>
      </section>

      <section className="space-y-3 rounded-xl border border-line p-4">
        <h2 className="text-sm font-bold uppercase tracking-wide text-muted">Security</h2>
        <input type="password" value={passwords.currentPassword} onChange={(event) => setPasswords({ ...passwords, currentPassword: event.target.value })} placeholder="Current password" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm" />
        <input type="password" value={passwords.newPassword} onChange={(event) => setPasswords({ ...passwords, newPassword: event.target.value })} placeholder="New password (min 8 characters)" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm" />
        <Button size="sm" onClick={async () => {
          await api("/api/me", { method: "POST", json: { action: "password", ...passwords } }).catch((e) => toast(e.message));
          toast("Password updated");
          setPasswords({ currentPassword: "", newPassword: "" });
        }}>
          Update password
        </Button>
      </section>

      <section className="space-y-2 rounded-xl border border-line p-4">
        <h2 className="text-sm font-bold uppercase tracking-wide text-muted">Subscriptions ({me.subscriptions.length})</h2>
        {me.subscriptions.map((sub) => (
          <div key={sub.channelId} className="flex items-center justify-between text-sm">
            <Link href={`/channel/${sub.handle}`} className="hover:text-brand">{sub.name}</Link>
            <button onClick={async () => {
              await api(`/api/channels/${sub.handle}?mode=notify`, { method: "POST", json: { notify: !sub.notify } }).catch(() => undefined);
              const fresh = await api<Me>("/api/me").catch(() => null);
              if (fresh) setMe(fresh);
              toast("Notification preference updated");
            }} className="text-xs text-muted">
              {sub.notify ? "🔔 all" : "🔕 personalized"}
            </button>
          </div>
        ))}
      </section>

      <section className="space-y-2 rounded-xl border border-line p-4">
        <h2 className="text-sm font-bold uppercase tracking-wide text-muted">Memberships &amp; payments</h2>
        {me.memberships.map((membership) => (
          <p key={membership.id} className="flex justify-between text-sm">
            <span>{membership.channelName}</span>
            <span className="text-muted">{formatMoney(membership.priceCents)} / mo</span>
          </p>
        ))}
        {me.payments.slice(0, 6).map((payment) => (
          <p key={payment.id} className="flex justify-between text-xs text-muted">
            <span className="capitalize">{payment.kind.replace("_", " ")}</span>
            <span>{formatMoney(payment.amountCents)}</span>
          </p>
        ))}
        {me.memberships.length === 0 && me.payments.length === 0 ? <p className="text-sm text-muted">No memberships or payments yet.</p> : null}
      </section>

      <section className="space-y-2 rounded-xl border border-line p-4">
        <h2 className="text-sm font-bold uppercase tracking-wide text-muted">Blocked users ({me.blocked.length})</h2>
        {me.blocked.map((blocked) => (
          <div key={blocked.id} className="flex items-center justify-between text-sm">
            <span>{blocked.name}</span>
            <button onClick={async () => {
              await api("/api/me", { method: "POST", json: { action: "unblock", userId: blocked.id } }).catch((e) => toast(e.message));
              const fresh = await api<Me>("/api/me").catch(() => null);
              if (fresh) setMe(fresh);
              toast("Unblocked");
            }} className="text-xs text-brand">Unblock</button>
          </div>
        ))}
        {me.blocked.length === 0 ? <p className="text-sm text-muted">You have not blocked anyone.</p> : null}
      </section>
      {toastNode}
    </div>
  );
}
