'use client';

import { Check, Lock, Monitor, Moon, Phone, Sun, User as UserIcon } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useTheme } from 'next-themes';
import { toast } from 'sonner';

import { FormField } from '@/components/forms/form-field';
import { PageTitle } from '@/components/layout/page-header';
import { SectionCard } from '@/components/settings/section-card';
import { StickySaveBar } from '@/components/settings/sticky-save-bar';
import { TimeZoneCombobox } from '@/components/settings/time-zone-combobox';
import { Avatar } from '@/components/ui/avatar';
import { Input } from '@/components/ui/input';
import { ErrorState, ForbiddenState } from '@/components/ui/states';
import { Skeleton } from '@/components/ui/skeleton';
import { ApiError, api } from '@/lib/api-client';
import { useAuth } from '@/lib/auth';
import { cn } from '@/lib/utils';

interface Profile {
  id: string;
  email: string;
  name: string;
  phone?: string;
  timezone?: string;
  themePreference?: 'light' | 'dark' | 'system';
}

export default function ProfileSettingsPage() {
  const { status, refreshMe } = useAuth();
  const { setTheme } = useTheme();
  const [profile, setProfile] = useState<Profile | null>(null);
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [timezone, setTimezone] = useState('UTC');
  const [themePreference, setThemePreference] = useState<'light' | 'dark' | 'system'>('system');
  const [error, setError] = useState<ApiError | null>(null);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (status !== 'authenticated') return;
    void api<Profile>('/users/me')
      .then((data) => {
        setProfile(data);
        setName(data.name);
        setPhone(data.phone ?? '');
        setTimezone(data.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone);
        setThemePreference(data.themePreference ?? 'system');
      })
      .catch((reason: unknown) => setError(reason instanceof ApiError ? reason : null));
  }, [status]);

  if (status === 'anonymous') return <ForbiddenState />;
  if (error !== null) return <ErrorState message={error.message} requestId={error.requestId} />;
  if (profile === null) {
    return (
      <div className="grid gap-6" aria-hidden="true">
        <Skeleton className="h-72 rounded-xl" />
        <Skeleton className="h-48 rounded-xl" />
      </div>
    );
  }

  const dirty =
    name !== profile.name ||
    phone !== (profile.phone ?? '') ||
    timezone !== (profile.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone) ||
    themePreference !== (profile.themePreference ?? 'system');

  return (
    <div className="grid gap-6">
      <PageTitle title="Profile" breadcrumb="Settings" />
      <SectionCard title="Personal information" description="How you appear to your team.">
        <div className="flex items-center gap-4">
          <Avatar name={name.trim().length > 0 ? name : profile.name} size="xl" />
          <div className="min-w-0">
            <p className="truncate font-display text-h3 font-bold">{name.trim().length > 0 ? name : profile.name}</p>
            <p className="truncate text-small text-muted-foreground">{profile.email}</p>
          </div>
        </div>
        <div className="mt-6 grid gap-4 sm:grid-cols-2">
          <FormField id="profile-name" label="Full name">
            <Input id="profile-name" autoComplete="name" leading={<UserIcon />} value={name} onChange={(event) => setName(event.target.value)} required />
          </FormField>
          <FormField id="profile-email" label="Email" hint="Email changes are not available yet.">
            <Input id="profile-email" value={profile.email} readOnly leading={<Lock />} aria-describedby="profile-email-hint" />
          </FormField>
          <FormField id="profile-phone" label="Phone (optional)">
            <Input id="profile-phone" inputMode="tel" autoComplete="tel" leading={<Phone />} value={phone} onChange={(event) => setPhone(event.target.value)} />
          </FormField>
          <FormField id="profile-tz" label="Time zone">
            <TimeZoneCombobox id="profile-tz" value={timezone} onChange={setTimezone} />
          </FormField>
        </div>
      </SectionCard>

      <SectionCard title="Appearance" description="Applies right away on this device. Save to keep it for your account.">
        <fieldset>
          <legend className="sr-only">Theme</legend>
          <div className="grid gap-3 sm:grid-cols-3">
            {THEMES.map((option) => {
              const selected = themePreference === option.value;
              return (
                <label
                  key={option.value}
                  className={cn(
                    'relative cursor-pointer rounded-xl border bg-surface p-2 transition-[border-color,box-shadow] duration-180 has-[:focus-visible]:shadow-glow',
                    selected ? 'border-2 border-primary p-[7px]' : 'border-border hover:border-border-strong',
                  )}
                >
                  <input
                    type="radio"
                    name="theme"
                    value={option.value}
                    checked={selected}
                    onChange={() => {
                      setThemePreference(option.value);
                      setTheme(option.value);
                    }}
                    className="sr-only"
                  />
                  <ThemePreview kind={option.value} />
                  <span className="mt-2 flex items-center justify-between px-1 pb-1">
                    <span className="flex items-center gap-1.5 text-small font-semibold">
                      <option.icon className="h-4 w-4 text-muted-foreground" aria-hidden="true" />
                      {option.label}
                    </span>
                    <span
                      className={cn('grid h-5 w-5 place-items-center rounded-full bg-primary text-primary-foreground transition duration-180', selected ? 'scale-100 opacity-100' : 'scale-50 opacity-0')}
                      aria-hidden="true"
                    >
                      <Check className="h-3 w-3" strokeWidth={3} />
                    </span>
                  </span>
                </label>
              );
            })}
          </div>
        </fieldset>
      </SectionCard>

      <StickySaveBar
        dirty={dirty}
        saving={saving}
        onDiscard={() => {
          setName(profile.name);
          setPhone(profile.phone ?? '');
          setTimezone(profile.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone);
          setThemePreference(profile.themePreference ?? 'system');
          setTheme(profile.themePreference ?? 'system');
        }}
        onSave={() => {
          setSaving(true);
          void api<Profile>('/users/me', {
            method: 'PATCH',
            json: {
              name,
              phone: phone.trim().length === 0 ? null : phone.trim(),
              timezone,
              themePreference,
            },
          })
            .then(async (data) => {
              setProfile(data);
              setTheme(themePreference);
              await refreshMe();
              toast.success('Profile saved.');
            })
            .catch((reason: unknown) => toast.error(reason instanceof ApiError ? reason.message : 'Could not save profile.'))
            .finally(() => setSaving(false));
        }}
      />
    </div>
  );
}

const THEMES = [
  { value: 'light', label: 'Light', icon: Sun },
  { value: 'dark', label: 'Dark', icon: Moon },
  { value: 'system', label: 'System', icon: Monitor },
] as const;

/** Tiny drawn window mockups. Colors are fixed per preview so each card shows its own theme. */
function ThemePreview({ kind }: { kind: 'light' | 'dark' | 'system' }) {
  const frame = (dark: boolean, className?: string) => (
    <div className={cn('h-full w-full overflow-hidden', dark ? 'dark bg-background' : 'bg-[rgb(245_246_250)]', className)}>
      <div className={cn('flex h-full', dark ? '' : '[--surface:255_255_255] [--border:228_231_239] [--surface-muted:240_242_248]')}>
        <div className="w-1/4 border-r border-border bg-surface p-1.5">
          <div className="h-1.5 w-3/4 rounded-full bg-brand-gradient" />
          <div className="mt-2 grid gap-1">
            <div className="h-1 rounded-full bg-border" />
            <div className="h-1 rounded-full bg-border" />
            <div className="h-1 w-2/3 rounded-full bg-border" />
          </div>
        </div>
        <div className="flex-1 p-1.5">
          <div className="h-1.5 w-1/2 rounded-full bg-border" />
          <div className="mt-2 grid grid-cols-2 gap-1">
            <div className="h-5 rounded border border-border bg-surface" />
            <div className="h-5 rounded border border-border bg-surface" />
          </div>
          <div className="mt-1 h-6 rounded border border-border bg-surface" />
        </div>
      </div>
    </div>
  );
  return (
    <div className="aspect-[16/10] overflow-hidden rounded-lg border border-border" aria-hidden="true">
      {kind === 'light' ? frame(false) : null}
      {kind === 'dark' ? frame(true) : null}
      {kind === 'system' ? (
        <div className="relative h-full w-full">
          {frame(false)}
          <div className="absolute inset-0 [clip-path:polygon(55%_0,100%_0,100%_100%,45%_100%)]">{frame(true)}</div>
        </div>
      ) : null}
    </div>
  );
}
