'use client';

import {
  User,
  CreditCard,
  Sliders,
  ToggleRight,
  Link2,
  ChevronLeft,
  Check,
  LogOut,
} from 'lucide-react';
import Link from 'next/link';
import { useSearchParams, useRouter } from 'next/navigation';
import { useCallback, useEffect, useState } from 'react';
import { useTranslation } from '@/lib/localization/context';
import { cn } from '@/lib/utils';
import SettingsButton from '@/components/Settings/SettingsButton';
import { authClient, clearStoredAuthToken } from '@/lib/auth-client';

function SignOutButton() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const handleSignOut = async () => {
    setLoading(true);
    clearStoredAuthToken();
    await authClient.signOut();
    router.push('/');
    router.refresh();
    setLoading(false);
  };
  return (
    <button
      type="button"
      onClick={handleSignOut}
      disabled={loading}
      className="flex items-center gap-2 rounded-lg border border-light-200 dark:border-dark-200 px-3 py-2 text-sm text-black/70 dark:text-white/70 hover:bg-light-200 dark:hover:bg-dark-200 disabled:opacity-50"
    >
      <LogOut size={16} />
      Выйти
    </button>
  );
}

interface BillingPlan {
  id: string;
  name: string;
  priceMonthly: number;
  priceYearly: number;
  currency: string;
  features: string[];
}

interface Subscription {
  planId: string;
  status: string;
  period: string;
}

interface ConnectorItem {
  id: string;
  name: string;
  description: string;
  status: string;
}

interface MemoryItem {
  id: string;
  key: string;
  value: string;
  createdAt?: string;
}

function PersonalizeSection({
  token,
  t,
}: {
  token: string | null;
  t: (k: string) => string;
}) {
  const [memories, setMemories] = useState<MemoryItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [newKey, setNewKey] = useState('');
  const [newValue, setNewValue] = useState('');
  const [adding, setAdding] = useState(false);

  const fetchMemories = useCallback(() => {
    if (!token) {
      setMemories([]);
      setLoading(false);
      return;
    }
    fetch('/api/v1/memory', {
      headers: { Authorization: `Bearer ${token}` },
    })
      .then((r) => r.json())
      .then((d) => setMemories(d.items ?? []))
      .catch(() => setMemories([]))
      .finally(() => setLoading(false));
  }, [token]);

  useEffect(() => {
    setLoading(true);
    fetchMemories();
  }, [fetchMemories]);

  const handleDelete = async (id: string) => {
    if (!token) return;
    const res = await fetch(`/api/v1/memory/${id}`, {
      method: 'DELETE',
      headers: { Authorization: `Bearer ${token}` },
    });
    if (res.ok) fetchMemories();
  };

  const handleAdd = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!token || !newKey.trim() || !newValue.trim()) return;
    setAdding(true);
    const res = await fetch('/api/v1/memory', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({ key: newKey.trim(), value: newValue.trim() }),
    });
    setAdding(false);
    if (res.ok) {
      setNewKey('');
      setNewValue('');
      fetchMemories();
    }
  };

  return (
    <section className="space-y-4">
      <h2 className="text-lg font-medium dark:text-white">{t('profile.personalize')}</h2>
      <p className="text-sm text-black/60 dark:text-white/60">
        {t('profile.personalizeDesc')}
      </p>
      {!token ? (
        <div className="rounded-xl border border-light-200 dark:border-dark-200 bg-light-secondary dark:bg-dark-secondary p-6 space-y-3">
          <p className="text-black/60 dark:text-white/60">{t('profile.signInToView')}</p>
          <Link
            href="/sign-in"
            className="inline-flex items-center rounded-lg bg-[#EA580C] px-4 py-2 text-sm font-medium text-white hover:bg-[#EA580C]/90"
          >
            Войти
          </Link>
        </div>
      ) : loading ? (
        <div className="rounded-xl border border-light-200 dark:border-dark-200 bg-light-secondary dark:bg-dark-secondary p-6 animate-pulse">
          <div className="h-4 w-48 bg-light-200 dark:bg-dark-200 rounded" />
        </div>
      ) : (
        <div className="rounded-xl border border-light-200 dark:border-dark-200 bg-light-secondary dark:bg-dark-secondary p-6">
          <h3 className="text-sm font-medium text-black/80 dark:text-white/80 mb-2">
            AI Memory (Pro)
          </h3>
          <form onSubmit={handleAdd} className="mb-4 flex flex-wrap gap-2">
            <input
              type="text"
              placeholder="Key (e.g. favorite_tech)"
              value={newKey}
              onChange={(e) => setNewKey(e.target.value)}
              className="rounded-lg border border-light-200 dark:border-dark-200 bg-light-primary dark:bg-dark-primary px-3 py-1.5 text-sm min-w-[120px]"
            />
            <input
              type="text"
              placeholder="Value"
              value={newValue}
              onChange={(e) => setNewValue(e.target.value)}
              className="rounded-lg border border-light-200 dark:border-dark-200 bg-light-primary dark:bg-dark-primary px-3 py-1.5 text-sm min-w-[160px] flex-1"
            />
            <button
              type="submit"
              disabled={adding || !newKey.trim() || !newValue.trim()}
              className="rounded-lg bg-[#EA580C] px-3 py-1.5 text-sm text-white hover:bg-[#EA580C]/90 disabled:opacity-50"
            >
              Add
            </button>
          </form>
          {memories.length > 0 ? (
            <ul className="space-y-2">
              {memories.map((m) => (
                <li
                  key={m.id}
                  className="flex items-start justify-between gap-2 rounded-lg p-2 bg-light-primary dark:bg-dark-primary border border-light-200/50 dark:border-dark-200/50"
                >
                  <div className="min-w-0 flex-1">
                    <p className="text-sm font-medium truncate">{m.key}</p>
                    <p className="text-xs text-black/60 dark:text-white/60 truncate">{m.value}</p>
                  </div>
                  <button
                    type="button"
                    onClick={() => handleDelete(m.id)}
                    className="px-2 py-1 text-xs text-red-600 hover:bg-red-500/10 rounded"
                  >
                    Delete
                  </button>
                </li>
              ))}
            </ul>
          ) : (
            <p className="text-black/60 dark:text-white/60 text-sm">
              No memory items yet. Add above or use Pro search (balanced/quality) with an account.
            </p>
          )}
        </div>
      )}
    </section>
  );
}

function ConnectorsSection({
  t,
}: {
  t: (k: string) => string;
}) {
  const [connectors, setConnectors] = useState<{
    available: ConnectorItem[];
    connected: ConnectorItem[];
  } | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('/api/v1/connectors')
      .then((r) => r.json())
      .then((d) => setConnectors({ available: d.available ?? [], connected: d.connected ?? [] }))
      .catch(() => setConnectors({ available: [], connected: [] }))
      .finally(() => setLoading(false));
  }, []);

  const available = connectors?.available ?? [];
  const connected = connectors?.connected ?? [];

  return (
    <section className="space-y-4">
      <h2 className="text-lg font-medium dark:text-white">{t('profile.connectors')}</h2>
      <p className="text-sm text-black/60 dark:text-white/60">
        {t('profile.connectorsDesc')}
      </p>
      {loading ? (
        <div className="rounded-xl border border-light-200 dark:border-dark-200 bg-light-secondary dark:bg-dark-secondary p-6 animate-pulse">
          <div className="h-4 w-48 bg-light-200 dark:bg-dark-200 rounded" />
        </div>
      ) : available.length > 0 ? (
        <div className="space-y-3">
          {available.map((c) => {
            const isConnected = connected.some((x) => x.id === c.id);
            const isComingSoon = c.status === 'coming_soon';
            return (
              <div
                key={c.id}
                className="flex items-center justify-between rounded-xl border border-light-200 dark:border-dark-200 bg-light-secondary dark:bg-dark-secondary p-4"
              >
                <div>
                  <h3 className="font-medium dark:text-white">{c.name}</h3>
                  <p className="text-sm text-black/60 dark:text-white/60 mt-0.5">{c.description}</p>
                </div>
                <button
                  type="button"
                  disabled={isComingSoon}
                  className={cn(
                    'px-3 py-1.5 rounded-lg text-sm font-medium',
                    isComingSoon &&
                      'bg-light-200 dark:bg-dark-200 text-black/50 dark:text-white/50 cursor-not-allowed',
                    isConnected && !isComingSoon &&
                      'bg-green-500/20 text-green-700 dark:text-green-400',
                    !isConnected && !isComingSoon &&
                      'bg-[#EA580C] text-white hover:bg-[#EA580C]/90'
                  )}
                >
                  {isComingSoon ? t('profile.comingSoon') : isConnected ? t('profile.connected') ?? 'Connected' : t('profile.connect') ?? 'Connect'}
                </button>
              </div>
            );
          })}
        </div>
      ) : (
        <div className="rounded-xl border border-light-200 dark:border-dark-200 bg-light-secondary dark:bg-dark-secondary p-6">
          <p className="text-black/60 dark:text-white/60">{t('profile.comingSoon')}</p>
        </div>
      )}
    </section>
  );
}

interface ProfileData {
  userId: string;
  displayName: string | null;
  avatarUrl: string | null;
  timezone: string | null;
  locale: string | null;
  profileData: Record<string, unknown>;
  preferences: Record<string, unknown>;
  personalization: Record<string, unknown>;
}

function AccountProfileContent({
  session,
  token,
  SignOutButton,
}: {
  session: { user?: { id: string; name?: string; email?: string; image?: string } };
  token: string | null;
  SignOutButton: React.ComponentType;
}) {
  const [profile, setProfile] = useState<ProfileData | null>(null);
  const [displayName, setDisplayName] = useState('');
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (!token) return;
    fetch('/api/v1/profile', { headers: { Authorization: `Bearer ${token}` } })
      .then((r) => (r.ok ? r.json() : null))
      .then((p) => {
        if (p) {
          setProfile(p);
          setDisplayName(p.displayName ?? session.user?.name ?? '');
        } else {
          setDisplayName(session.user?.name ?? '');
        }
      })
      .catch(() => setDisplayName(session.user?.name ?? ''));
  }, [token, session.user?.name]);

  const handleSaveProfile = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!token) return;
    setSaving(true);
    try {
      const res = await fetch('/api/v1/profile', {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ displayName: displayName.trim() || null }),
      });
      if (res.ok) {
        const data = await res.json();
        setProfile(data);
      }
    } finally {
      setSaving(false);
    }
  };

  const avatarSrc = profile?.avatarUrl ?? session.user?.image ?? null;

  return (
    <div className="flex flex-col gap-6 sm:flex-row sm:items-start">
      <div className="flex items-center gap-4">
        {avatarSrc ? (
          <img src={avatarSrc} alt="" className="h-16 w-16 rounded-full object-cover" />
        ) : (
          <div className="flex h-16 w-16 items-center justify-center rounded-full bg-light-200 dark:bg-dark-200">
            <User size={28} className="text-black/50 dark:text-white/50" />
          </div>
        )}
        <div className="flex-1">
          <p className="font-medium text-black dark:text-white">
            {profile?.displayName ?? session.user?.name ?? '—'}
          </p>
          <p className="text-sm text-black/60 dark:text-white/60">
            {session.user?.email ?? '—'}
          </p>
          <p className="text-xs text-black/50 dark:text-white/50 mt-1">
            ID: {session.user?.id}
          </p>
        </div>
        <SignOutButton />
      </div>
      {token && (
        <form onSubmit={handleSaveProfile} className="flex flex-col gap-3 sm:border-l sm:border-light-200 sm:dark:border-dark-200 sm:pl-6">
          <label className="text-sm font-medium text-black dark:text-white">
            Отображаемое имя
          </label>
          <input
            type="text"
            value={displayName}
            onChange={(e) => setDisplayName(e.target.value)}
            placeholder={session.user?.name ?? ''}
            className="rounded-lg border border-light-200 dark:border-dark-200 bg-light-primary dark:bg-dark-primary px-3 py-2 text-sm text-black dark:text-white"
          />
          <button
            type="submit"
            disabled={saving}
            className="self-start rounded-lg bg-[#EA580C] px-4 py-2 text-sm font-medium text-white hover:bg-[#EA580C]/90 disabled:opacity-50"
          >
            {saving ? 'Сохранение…' : 'Сохранить'}
          </button>
        </form>
      )}
    </div>
  );
}

const SECTIONS = [
  { key: 'account', labelKey: 'profile.account', icon: User },
  { key: 'preferences', labelKey: 'profile.preferences', icon: Sliders },
  { key: 'personalize', labelKey: 'profile.personalize', icon: ToggleRight },
  { key: 'billing', labelKey: 'profile.billing', icon: CreditCard },
  { key: 'connectors', labelKey: 'profile.connectors', icon: Link2 },
] as const;

export default function ProfilePage() {
  const searchParams = useSearchParams();
  const tab = (searchParams.get('tab') ?? 'account') as (typeof SECTIONS)[number]['key'];
  const { t } = useTranslation();

  const [session, setSession] = useState<{ user?: { id: string; name?: string; email?: string; image?: string } } | null>(null);
  const [plans, setPlans] = useState<BillingPlan[]>([]);
  const [subscription, setSubscription] = useState<Subscription | null>(null);
  const [payments, setPayments] = useState<{ id: string; planId: string; amount: number; currency: string; status: string; createdAt: string }[]>([]);
  const [loading, setLoading] = useState(true);
  const [checkoutLoading, setCheckoutLoading] = useState<string | null>(null);

  const token =
    typeof window !== 'undefined'
      ? localStorage.getItem('auth_token') ?? localStorage.getItem('access_token')
      : null;

  useEffect(() => {
    const fetchSession = async () => {
      try {
        const res = await fetch('/api/auth/get-session');
        if (res.ok) {
          const data = await res.json();
          setSession(data?.data ?? null);
        }
      } catch {
        setSession(null);
      }
    };
    fetchSession();
  }, []);

  useEffect(() => {
    const fetchPlans = async () => {
      try {
        const res = await fetch('/api/v1/billing/plans');
        if (res.ok) {
          const data = await res.json();
          setPlans(Array.isArray(data) ? data : data.plans ?? []);
        }
      } catch {
        setPlans([]);
      }
    };
    fetchPlans();
  }, []);

  useEffect(() => {
    if (!token) return;
    const fetchSubscription = async () => {
      try {
        const res = await fetch('/api/v1/billing/subscription', {
          headers: { Authorization: `Bearer ${token}` },
        });
        if (res.ok) {
          const data = await res.json();
          setSubscription(data);
        }
      } catch {
        setSubscription(null);
      }
    };
    fetchSubscription();
  }, [token]);

  useEffect(() => {
    if (!token) return;
    const fetchPayments = async () => {
      try {
        const res = await fetch('/api/v1/billing/payments', {
          headers: { Authorization: `Bearer ${token}` },
        });
        if (res.ok) {
          const data = await res.json();
          setPayments(data.payments ?? []);
        }
      } catch {
        setPayments([]);
      }
    };
    fetchPayments();
  }, [token]);

  useEffect(() => {
    setLoading(false);
  }, [session, plans]);

  const handleCheckout = async (planId: string, period: 'monthly' | 'yearly') => {
    if (!token) return;
    setCheckoutLoading(planId);
    try {
      const res = await fetch('/api/v1/billing/checkout', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ planId, period }),
      });
      const data = await res.json();
      if (data.redirectUrl) {
        window.location.href = data.redirectUrl;
      } else if (res.ok) {
        setSubscription({ planId, status: 'pending', period });
      }
    } catch {
      // error handling
    } finally {
      setCheckoutLoading(null);
    }
  };

  const formatPrice = (cents: number, currency: string) => {
    const val = cents / 100;
    return new Intl.NumberFormat('ru-RU', {
      style: 'currency',
      currency: currency === 'RUB' ? 'RUB' : 'USD',
      minimumFractionDigits: 0,
    }).format(val);
  };

  const currentPlanId = subscription?.planId ?? 'free';

  return (
    <div className="min-h-screen bg-light-primary dark:bg-dark-primary">
      <div className="mx-auto max-w-4xl px-4 py-8">
        <Link
          href="/"
          className="mb-6 inline-flex items-center gap-2 text-sm text-black/60 hover:text-black dark:text-white/60 hover:dark:text-white"
        >
          <ChevronLeft size={18} />
          {t('nav.home')}
        </Link>

        <div className="flex flex-col gap-8 lg:flex-row">
          <nav className="flex shrink-0 flex-col gap-1 lg:w-56">
            {SECTIONS.map((s) => (
              <Link
                key={s.key}
                href={`/profile?tab=${s.key}`}
                className={cn(
                  'flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm transition-colors',
                  tab === s.key
                    ? 'bg-light-200 text-black dark:bg-dark-200 dark:text-white'
                    : 'text-black/70 hover:bg-light-200/50 dark:text-white/70 hover:dark:bg-dark-200/50'
                )}
              >
                <s.icon size={18} />
                {t(s.labelKey)}
              </Link>
            ))}
            <div className="mt-4 border-t border-light-200 dark:border-dark-200 pt-4">
              <div className="flex items-center gap-2">
                <SettingsButton />
                <span className="text-sm text-black/60 dark:text-white/60">
                  {t('profile.appSettings')}
                </span>
              </div>
            </div>
          </nav>

          <main className="flex-1">
            {tab === 'account' && (
              <section className="space-y-4">
                <h2 className="text-lg font-medium dark:text-white">{t('profile.account')}</h2>
                <div className="rounded-xl border border-light-200 dark:border-dark-200 bg-light-secondary dark:bg-dark-secondary p-6">
                  {session?.user ? (
                    <AccountProfileContent
                      session={session}
                      token={token}
                      SignOutButton={SignOutButton}
                    />
                  ) : (
                    <div className="space-y-3">
                      <p className="text-black/60 dark:text-white/60">
                        {t('profile.signInToView')}
                      </p>
                      <Link
                        href="/sign-in"
                        className="inline-flex items-center rounded-lg bg-[#EA580C] px-4 py-2 text-sm font-medium text-white hover:bg-[#EA580C]/90"
                      >
                        Войти
                      </Link>
                    </div>
                  )}
                </div>
              </section>
            )}

            {tab === 'preferences' && (
              <section className="space-y-4">
                <h2 className="text-lg font-medium dark:text-white">{t('profile.preferences')}</h2>
                <p className="text-sm text-black/60 dark:text-white/60">
                  {t('profile.preferencesDesc')}
                </p>
                <div className="rounded-xl border border-light-200 dark:border-dark-200 bg-light-secondary dark:bg-dark-secondary p-6">
                  <SettingsButton />
                </div>
              </section>
            )}

            {tab === 'personalize' && (
              <PersonalizeSection token={token} t={t} />
            )}

            {tab === 'billing' && (
              <section className="space-y-6">
                <h2 className="text-lg font-medium dark:text-white">{t('profile.billing')}</h2>

                {loading ? (
                  <div className="h-32 animate-pulse rounded-xl bg-light-200 dark:bg-dark-200" />
                ) : (
                  <>
                    <div className="grid gap-4 sm:grid-cols-3">
                      {plans.map((plan) => {
                        const isCurrent = currentPlanId === plan.id;
                        const isFree = plan.id === 'free';
                        return (
                          <div
                            key={plan.id}
                            className={cn(
                              'rounded-xl border p-6 transition-colors',
                              isCurrent
                                ? 'border-black dark:border-white bg-light-200/50 dark:bg-dark-200/50'
                                : 'border-light-200 dark:border-dark-200 bg-light-secondary dark:bg-dark-secondary'
                            )}
                          >
                            <div className="flex items-center justify-between">
                              <h3 className="font-medium text-black dark:text-white">
                                {plan.name}
                              </h3>
                              {isCurrent && (
                                <span className="flex items-center gap-1 rounded-full bg-green-500/20 px-2 py-0.5 text-xs text-green-700 dark:text-green-400">
                                  <Check size={12} />
                                  {t('profile.current')}
                                </span>
                              )}
                            </div>
                            <div className="mt-2">
                              <span className="text-2xl font-semibold text-black dark:text-white">
                                {formatPrice(plan.priceMonthly, plan.currency)}
                              </span>
                              <span className="text-sm text-black/60 dark:text-white/60">
                                /{t('profile.month')}
                              </span>
                            </div>
                            <ul className="mt-4 space-y-1.5 text-sm text-black/80 dark:text-white/80">
                              {plan.features.slice(0, 4).map((f, i) => (
                                <li key={i} className="flex items-start gap-2">
                                  <Check size={14} className="mt-0.5 shrink-0 text-green-600" />
                                  {f}
                                </li>
                              ))}
                            </ul>
                            {!isFree && !isCurrent && token && (
                              <button
                                onClick={() => handleCheckout(plan.id, 'monthly')}
                                disabled={!!checkoutLoading}
                                className="mt-4 w-full rounded-lg bg-black px-4 py-2 text-sm font-medium text-white hover:opacity-90 disabled:opacity-50 dark:bg-white dark:text-black"
                              >
                                {checkoutLoading === plan.id
                                  ? t('common.loading')
                                  : t('profile.upgrade')}
                              </button>
                            )}
                          </div>
                        );
                      })}
                    </div>

                    {token && payments.length > 0 && (
                      <div className="rounded-xl border border-light-200 dark:border-dark-200 bg-light-secondary dark:bg-dark-secondary p-6">
                        <h3 className="mb-3 font-medium text-black dark:text-white">
                          {t('profile.paymentHistory')}
                        </h3>
                        <div className="space-y-2">
                          {payments.slice(0, 10).map((p) => (
                            <div
                              key={p.id}
                              className="flex flex-wrap items-center justify-between gap-2 rounded-lg bg-light-200/50 dark:bg-dark-200/50 px-3 py-2 text-sm"
                            >
                              <span className="text-black dark:text-white">
                                {p.planId} · {formatPrice(p.amount, p.currency)}
                              </span>
                              <span className="text-black/50 dark:text-white/50">
                                {new Date(p.createdAt).toLocaleDateString()}
                              </span>
                              <span
                                className={cn(
                                  'rounded px-2 py-0.5 text-xs capitalize',
                                  p.status === 'succeeded'
                                    ? 'bg-green-500/20 text-green-700 dark:text-green-400'
                                    : p.status === 'pending'
                                      ? 'bg-amber-500/20 text-amber-700 dark:text-amber-400'
                                      : 'bg-red-500/20 text-red-700 dark:text-red-400'
                                )}
                              >
                                {p.status}
                              </span>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </>
                )}
              </section>
            )}

            {tab === 'connectors' && (
              <ConnectorsSection t={t} />
            )}
          </main>
        </div>
      </div>
    </div>
  );
}
