import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Clock, Globe, Languages, Link, User } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';

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

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

const TIMEZONES = [
  { value: '', label: 'Select timezone…' },
  { value: 'Asia/Shanghai', label: 'Asia/Shanghai (UTC+8)' },
  { value: 'Asia/Tokyo', label: 'Asia/Tokyo (UTC+9)' },
  { value: 'Asia/Singapore', label: 'Asia/Singapore (UTC+8)' },
  { value: 'America/New_York', label: 'America/New_York (UTC-5)' },
  { value: 'America/Chicago', label: 'America/Chicago (UTC-6)' },
  { value: 'America/Los_Angeles', label: 'America/Los_Angeles (UTC-8)' },
  { value: 'Europe/London', label: 'Europe/London (UTC+0)' },
  { value: 'Europe/Berlin', label: 'Europe/Berlin (UTC+1)' },
  { value: 'Europe/Paris', label: 'Europe/Paris (UTC+1)' },
  { value: 'Pacific/Auckland', label: 'Pacific/Auckland (UTC+12)' },
] as const;

const LANGUAGES = [
  { value: '', label: 'Select language…' },
  { value: 'en', label: 'English' },
  { value: 'zh-CN', label: '简体中文' },
  { value: 'zh-TW', label: '繁體中文' },
  { value: 'ja', label: '日本語' },
  { value: 'ko', label: '한국어' },
  { value: 'de', label: 'Deutsch' },
  { value: 'fr', label: 'Français' },
  { value: 'es', label: 'Español' },
] as const;

export function ProfileTab() {
  const { data: profile, isLoading, error } = useUserProfile();
  const queryClient = useQueryClient();

  const [form, setForm] = useState({
    full_name: '',
    company: '',
    location: '',
    website_url: '',
    twitter_username: '',
    timezone: '',
    language: '',
    profile_readme: '',
  });
  const [saved, setSaved] = useState(false);

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

  const isInitialized = useRef(false);
  useEffect(() => {
    if (profile && !isInitialized.current) {
      isInitialized.current = true;
      setForm({
        full_name: profile.full_name ?? '',
        company: profile.company ?? '',
        location: profile.location ?? '',
        website_url: profile.website_url ?? '',
        twitter_username: profile.twitter_username ?? '',
        timezone: profile.timezone ?? '',
        language: profile.language ?? '',
        profile_readme: profile.profile_readme ?? '',
      });
    }
  }, [profile]);

  function handleSave() {
    updateMutation.mutate({
      full_name: form.full_name || undefined,
      company: form.company || undefined,
      location: form.location || undefined,
      website_url: form.website_url || undefined,
      twitter_username: form.twitter_username || undefined,
      timezone: form.timezone || undefined,
      language: form.language || undefined,
      profile_readme: form.profile_readme || 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 profile.
        </div>
      </div>
    );
  }

  return (
    <div className="px-8 pt-10 pb-8">
      <SectionHeading
        title="Public profile details"
        description="Complete your profile to help others know you better."
      />

      <div className="max-w-[480px]">
        <FieldGroup label="Full name" htmlFor="profile-full-name">
          <TextInput
            id="profile-full-name"
            value={form.full_name}
            onChange={(v) => setForm((prev) => ({ ...prev, full_name: v }))}
            placeholder="Your full name"
            icon={User}
          />
        </FieldGroup>

        <FieldGroup label="Company" htmlFor="profile-company">
          <TextInput
            id="profile-company"
            value={form.company}
            onChange={(v) => setForm((prev) => ({ ...prev, company: v }))}
            placeholder="Your company or organization"
            icon={Globe}
          />
        </FieldGroup>

        <FieldGroup label="Location" htmlFor="profile-location">
          <TextInput
            id="profile-location"
            value={form.location}
            onChange={(v) => setForm((prev) => ({ ...prev, location: v }))}
            placeholder="e.g. San Francisco, CA"
            icon={Globe}
          />
        </FieldGroup>

        <FieldGroup label="Website" htmlFor="profile-website">
          <TextInput
            id="profile-website"
            value={form.website_url}
            onChange={(v) => setForm((prev) => ({ ...prev, website_url: v }))}
            placeholder="https://example.com"
            icon={Link}
          />
        </FieldGroup>

        <FieldGroup label="Twitter username" htmlFor="profile-twitter">
          <TextInput
            id="profile-twitter"
            value={form.twitter_username}
            onChange={(v) => setForm((prev) => ({ ...prev, twitter_username: v }))}
            placeholder="@username"
            icon={Link}
          />
        </FieldGroup>

        <FieldGroup label="Timezone" htmlFor="profile-timezone">
          <div className="relative">
            <Clock className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
            <select
              id="profile-timezone"
              value={form.timezone}
              onChange={(e) => setForm((prev) => ({ ...prev, timezone: e.target.value }))}
              className="w-full rounded-md border border-border bg-card py-[7px] pl-9 pr-3 text-[14px] leading-[20px] text-foreground outline-none transition-shadow focus:shadow-[inset_0_0_0_2px_var(--ring)] focus:border-transparent"
            >
              {TIMEZONES.map((tz) => (
                <option key={tz.value} value={tz.value}>
                  {tz.label}
                </option>
              ))}
            </select>
          </div>
        </FieldGroup>

        <FieldGroup label="Language" htmlFor="profile-language">
          <div className="relative">
            <Languages className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
            <select
              id="profile-language"
              value={form.language}
              onChange={(e) => setForm((prev) => ({ ...prev, language: e.target.value }))}
              className="w-full rounded-md border border-border bg-card py-[7px] pl-9 pr-3 text-[14px] leading-[20px] text-foreground outline-none transition-shadow focus:shadow-[inset_0_0_0_2px_var(--ring)] focus:border-transparent"
            >
              {LANGUAGES.map((lang) => (
                <option key={lang.value} value={lang.value}>
                  {lang.label}
                </option>
              ))}
            </select>
          </div>
        </FieldGroup>

        <FieldGroup
          label="Profile README"
          htmlFor="profile-readme"
          helpText="A personal README shown on your profile. Markdown supported."
        >
          <TextInput
            id="profile-readme"
            as="textarea"
            rows={6}
            value={form.profile_readme}
            onChange={(v) => setForm((prev) => ({ ...prev, profile_readme: v }))}
            placeholder="Share a little about yourself, your interests, and what you're working on…"
          />
        </FieldGroup>
      </div>

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