import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useEffect, useRef, useState } from 'react';

import { UserService } from '@/client/services/UserService';
import { useCurrentUser } from '@/hooks/user/useCurrentUser';
import { useUserAccount } from '@/hooks/user/useUserAccount';

import { FieldGroup, SaveBar, SectionHeading, SelectInput, TextInput } from './primitives';

export function AccountTab() {
  const { data: account, isLoading, error } = useUserAccount();
  const { data: user } = useCurrentUser();
  const queryClient = useQueryClient();

  const [form, setForm] = useState({
    username: '',
    display_name: '',
    bio: '',
    visibility: 'public',
  });
  const [saved, setSaved] = useState(false);

  const updateMutation = useMutation({
    mutationFn: (body: Record<string, string | undefined>) =>
      UserService.userUpdateAccount({ requestBody: body }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['user', 'account'] });
      queryClient.invalidateQueries({ queryKey: ['auth', 'me'] });
      setSaved(true);
      setTimeout(() => setSaved(false), 2500);
    },
  });

  const isInitialized = useRef(false);
  useEffect(() => {
    if (account && !isInitialized.current) {
      isInitialized.current = true;
      setForm({
        username: account.username ?? '',
        display_name: account.display_name ?? '',
        bio: account.bio ?? '',
        visibility: account.visibility ?? 'public',
      });
    }
  }, [account]);

  function handleSave() {
    updateMutation.mutate({
      username: form.username || undefined,
      display_name: form.display_name || undefined,
      bio: form.bio || undefined,
      visibility: form.visibility || undefined,
    });
  }

  if (isLoading) {
    return (
      <div className="flex items-center gap-2 p-8 text-[14px] text-muted-foreground">
        <span className="inline-block size-4 animate-spin rounded-full border-2 border-border border-t-muted-foreground" />
        Loading…
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-8">
        <div className="rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-[14px] text-destructive">
          Failed to load account settings.
        </div>
      </div>
    );
  }

  return (
    <div>
      {/* Profile header */}
      <div className="px-8 pt-10 pb-6">
        <div className="flex items-center gap-4">
          <img
            src={
              user?.avatar_url ?? `https://avatar.vercel.sh/${user?.username ?? 'u'}.svg?size=80`
            }
            alt={user?.username ?? 'User avatar'}
            className="size-[72px] shrink-0 rounded-full border border-border/60 shadow-sm"
          />
          <div>
            <h1 className="text-[20px] font-semibold text-foreground">
              {user?.display_name ?? user?.username ?? '—'}
            </h1>
            <p className="text-[14px] text-muted-foreground">{user?.username ?? '—'}</p>
          </div>
        </div>
      </div>

      <div className="px-8 pb-8">
        <SectionHeading
          title="Public profile"
          description="This information will appear on your public profile."
        />

        <div className="max-w-[480px]">
          <FieldGroup
            label="Username"
            htmlFor="acct-username"
            helpText="Your unique handle on the platform. Can only be changed once every 30 days."
          >
            <TextInput
              id="acct-username"
              value={form.username}
              onChange={(v) => setForm((f) => ({ ...f, username: v }))}
              placeholder="your-username"
            />
          </FieldGroup>

          <FieldGroup
            label="Display name"
            htmlFor="acct-display-name"
            helpText="How your name appears across the platform."
          >
            <TextInput
              id="acct-display-name"
              value={form.display_name}
              onChange={(v) => setForm((f) => ({ ...f, display_name: v }))}
              placeholder="Your Name"
            />
          </FieldGroup>

          <FieldGroup
            label="Bio"
            htmlFor="acct-bio"
            helpText="A short description about you. Markdown supported."
          >
            <TextInput
              id="acct-bio"
              as="textarea"
              rows={3}
              value={form.bio}
              onChange={(v) => setForm((f) => ({ ...f, bio: v }))}
              placeholder="Tell us a little about yourself"
            />
          </FieldGroup>

          <FieldGroup label="Profile visibility" htmlFor="acct-visibility">
            <SelectInput
              id="acct-visibility"
              value={form.visibility}
              onChange={(v) => setForm((f) => ({ ...f, visibility: v }))}
              options={[
                { value: 'public', label: 'Public — visible to everyone' },
                { value: 'private', label: 'Private — visible only to you' },
                { value: 'internal', label: 'Internal — visible to workspace members' },
              ]}
            />
          </FieldGroup>

          <SaveBar
            isPending={updateMutation.isPending}
            saved={saved}
            error={updateMutation.error as Error | null}
            onSave={handleSave}
          />
        </div>
      </div>
    </div>
  );
}
