"use client";

import { useCallback, useEffect, useState } from "react";
import { api, auth } from "@/lib/api";
import { PageHeader, Card, Button, Input, Checkbox, FormField, Skeleton } from "@/components/ui";
import { useToast } from "@/components/toast";

export default function SettingsPage() {
  const toast = useToast();
  const [profile, setProfile] = useState<{ name: string; email: string; socialHandle: string; website: string; avatarUrl: string } | null>(null);
  const [referralCode, setReferralCode] = useState("");
  const [savingRc, setSavingRc] = useState(false);
  const [notify, setNotify] = useState({ sale: true, payout: true });
  const [savingN, setSavingN] = useState(false);
  const [pwd, setPwd] = useState({ currentPassword: "", newPassword: "", confirm: "" });
  const [savingP, setSavingP] = useState(false);
  const [savingPw, setSavingPw] = useState(false);
  const [pErr, setPErr] = useState<Record<string, string>>({});
  const [pwErr, setPwErr] = useState<Record<string, string>>({});

  const load = useCallback(async () => {
    const id = auth.get()?.id;
    if (!id) return;
    const d = await api.get(`/affiliates/${id}`);
    setProfile({ name: d.name ?? "", email: d.email ?? "", socialHandle: d.socialHandle ?? "", website: d.website ?? "", avatarUrl: d.avatarUrl ?? "" });
    setReferralCode(d.couponCode ?? "");
    setNotify({ sale: d.notifyPrefs?.sale !== false, payout: d.notifyPrefs?.payout !== false });
  }, []);

  const saveReferralCode = async () => {
    const id = auth.get()?.id;
    if (!id) return;
    setSavingRc(true);
    try {
      const r = await api.post(`/affiliates/${id}/referral-code`, { code: referralCode });
      setReferralCode(r.code);
      toast.success("Referral code updated.");
    } catch (e) {
      toast.error((e as Error).message);
    } finally {
      setSavingRc(false);
    }
  };

  const saveNotify = async () => {
    const id = auth.get()?.id;
    if (!id) return;
    setSavingN(true);
    try {
      await api.post(`/affiliates/${id}/notifications`, notify);
      toast.success("Notification preferences saved.");
    } catch (e) {
      toast.error((e as Error).message);
    } finally {
      setSavingN(false);
    }
  };

  useEffect(() => {
    load();
  }, [load]);

  const saveProfile = async () => {
    const id = auth.get()?.id;
    if (!id || !profile) return;
    if (!profile.name.trim()) {
      setPErr({ name: "Name is required." });
      return;
    }
    setPErr({});
    setSavingP(true);
    try {
      await api.post(`/affiliates/${id}/profile`, { name: profile.name, socialHandle: profile.socialHandle, website: profile.website, avatarUrl: profile.avatarUrl });
      auth.save(id, profile.name); // keep the top-bar name in sync
      toast.success("Profile updated.");
    } catch (e) {
      toast.error((e as Error).message);
    } finally {
      setSavingP(false);
    }
  };

  const savePassword = async () => {
    const id = auth.get()?.id;
    if (!id) return;
    const e: Record<string, string> = {};
    if (!pwd.currentPassword) e.currentPassword = "Enter your current password.";
    if (pwd.newPassword.length < 4) e.newPassword = "At least 4 characters.";
    if (pwd.newPassword !== pwd.confirm) e.confirm = "Passwords don't match.";
    setPwErr(e);
    if (Object.keys(e).length) return;
    setSavingPw(true);
    try {
      await api.post(`/affiliates/${id}/password`, { currentPassword: pwd.currentPassword, newPassword: pwd.newPassword });
      toast.success("Password changed.");
      setPwd({ currentPassword: "", newPassword: "", confirm: "" });
    } catch (err) {
      toast.error((err as Error).message);
    } finally {
      setSavingPw(false);
    }
  };

  if (!profile) return <div className="space-y-4"><Skeleton className="h-8 w-40" /><Skeleton className="h-56" /></div>;

  return (
    <div className="max-w-2xl">
      <PageHeader title="Settings" subtitle="Manage your account" />

      <div className="space-y-4">
        <Card title="Profile">
          <div className="grid gap-4 sm:grid-cols-2">
            <FormField label="Full name" required error={pErr.name}>
              <Input error={!!pErr.name} value={profile.name} onChange={(e) => setProfile({ ...profile, name: e.target.value })} />
            </FormField>
            <FormField label="Email" hint="Contact the brand to change your email">
              <Input value={profile.email} disabled />
            </FormField>
            <FormField label="Social handle">
              <Input value={profile.socialHandle} onChange={(e) => setProfile({ ...profile, socialHandle: e.target.value })} placeholder="@handle" />
            </FormField>
            <FormField label="Website">
              <Input value={profile.website} onChange={(e) => setProfile({ ...profile, website: e.target.value })} placeholder="https://…" />
            </FormField>
            <div className="sm:col-span-2">
              <FormField label="Profile photo URL" hint="Link to your photo (shown in your portal)">
                <Input value={profile.avatarUrl} onChange={(e) => setProfile({ ...profile, avatarUrl: e.target.value })} placeholder="https://…/me.jpg" />
              </FormField>
            </div>
          </div>
          <div className="mt-4">
            <Button loading={savingP} onClick={saveProfile}>Save profile</Button>
          </div>
        </Card>

        <Card title="Referral code" subtitle="Customize the code in your link & coupon">
          <div className="flex flex-col gap-3 sm:flex-row sm:items-end">
            <div className="flex-1">
              <FormField label="Your code" hint="3+ letters/numbers, must be unique">
                <Input value={referralCode} onChange={(e) => setReferralCode(e.target.value.toUpperCase())} className="font-mono" />
              </FormField>
            </div>
            <Button loading={savingRc} onClick={saveReferralCode}>Update code</Button>
          </div>
        </Card>

        <Card title="Change password">
          <div className="grid gap-4 sm:grid-cols-2">
            <div className="sm:col-span-2">
              <FormField label="Current password" error={pwErr.currentPassword}>
                <Input type="password" error={!!pwErr.currentPassword} value={pwd.currentPassword} onChange={(e) => setPwd({ ...pwd, currentPassword: e.target.value })} />
              </FormField>
            </div>
            <FormField label="New password" error={pwErr.newPassword}>
              <Input type="password" error={!!pwErr.newPassword} value={pwd.newPassword} onChange={(e) => setPwd({ ...pwd, newPassword: e.target.value })} />
            </FormField>
            <FormField label="Confirm new password" error={pwErr.confirm}>
              <Input type="password" error={!!pwErr.confirm} value={pwd.confirm} onChange={(e) => setPwd({ ...pwd, confirm: e.target.value })} />
            </FormField>
          </div>
          <div className="mt-4">
            <Button loading={savingPw} onClick={savePassword}>Change password</Button>
          </div>
        </Card>

        <Card title="Email notifications">
          <div className="space-y-3">
            <Checkbox label="Email me when I earn a commission" checked={notify.sale} onChange={(e) => setNotify({ ...notify, sale: e.target.checked })} />
            <Checkbox label="Email me when I get paid" checked={notify.payout} onChange={(e) => setNotify({ ...notify, payout: e.target.checked })} />
          </div>
          <div className="mt-4">
            <Button loading={savingN} onClick={saveNotify}>Save preferences</Button>
          </div>
        </Card>
      </div>
    </div>
  );
}
