import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  ChevronRight,
  LogOut,
  Info,
  Shield,
  Mail,
  Mic,
  LifeBuoy,
  FileText,
  Volume2,
  ArrowLeft,
  Camera,
  Sun,
  Moon,
  Monitor,
  Palette,
} from 'lucide-react';
import { HumanAvatar } from '@/components/human-avatar';
import { AvatarEditDialog } from '@/features/settings/avatar-edit-dialog';
import { Separator } from '@/components/ui/separator';
import { Switch } from '@/components/ui/switch';
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { WindowControls } from '@/components/window-controls';
import { Button } from '@/components/ui/button';
import { Muted } from '@/components/ui/typography';
import { ScrollArea } from '@/components/ui/scroll-area';
import { CopyableEmail } from '@/components/copyable-email';
import { useAuthStore } from '@/stores/auth-store';
import { useSoundEffectsStore } from '@/stores/sound-effects-store';
import { useThemeStore, type ThemeMode } from '@/stores/theme-store';
import { apiClient } from '@/api/client';
import { logError, toUserMessage } from '@/lib/errors';
import { toast } from 'sonner';
import { PRIVACY_URL, SUPPORT_EMAIL, TERMS_URL } from '@/lib/constants';
import { platform } from '@/lib/platform';

interface SettingsRowProps {
  icon: React.ReactNode;
  label: string;
  detail?: string;
  onClick?: () => void;
  destructive?: boolean;
}

function SettingsRow({
  icon,
  label,
  detail,
  onClick,
  destructive,
}: SettingsRowProps) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`flex w-full items-center gap-3 px-4 py-3 text-left transition-colors hover:bg-accent ${destructive ? 'text-destructive' : ''}`}
    >
      <span className="text-muted-foreground flex size-5 items-center justify-center">
        {icon}
      </span>
      <span className="min-w-0 flex-1 text-sm font-medium">{label}</span>
      {detail && <Muted className="text-xs">{detail}</Muted>}
      {onClick && !destructive && (
        <ChevronRight className="text-muted-foreground size-4" />
      )}
    </button>
  );
}

function SettingsGroup({
  title,
  children,
}: {
  title: string;
  children: React.ReactNode;
}) {
  return (
    <div>
      <p className="text-muted-foreground px-4 pb-1 pt-4 text-xs font-medium uppercase tracking-wider">
        {title}
      </p>
      <div>{children}</div>
    </div>
  );
}

const THEME_OPTIONS: {
  value: ThemeMode;
  label: string;
  icon: React.ReactNode;
}[] = [
  { value: 'system', label: 'System', icon: <Monitor className="size-3.5" /> },
  { value: 'light', label: 'Light', icon: <Sun className="size-3.5" /> },
  { value: 'dark', label: 'Dark', icon: <Moon className="size-3.5" /> },
];

function ThemeSetting() {
  const mode = useThemeStore((s) => s.mode);
  const setMode = useThemeStore((s) => s.setMode);

  return (
    <div className="flex w-full items-center gap-3 px-4 py-3">
      <span className="text-muted-foreground flex size-5 items-center justify-center">
        <Palette className="size-4" />
      </span>
      <span className="min-w-0 flex-1 text-sm font-medium">Theme</span>
      <ToggleGroup
        type="single"
        size="sm"
        value={mode}
        onValueChange={(value) => value && setMode(value as ThemeMode)}
        className="border-border bg-muted/50 border p-0.5"
        spacing={2}
      >
        {THEME_OPTIONS.map((option) => (
          <ToggleGroupItem
            key={option.value}
            value={option.value}
            aria-label={option.label}
            className="data-[state=on]:bg-background data-[state=on]:text-foreground data-[state=on]:shadow-sm gap-1.5 rounded-md px-2.5 text-xs"
          >
            {option.icon}
            {option.label}
          </ToggleGroupItem>
        ))}
      </ToggleGroup>
    </div>
  );
}

export default function SettingsPage() {
  const navigate = useNavigate();
  const user = useAuthStore((s) => s.user);
  const signOut = useAuthStore((s) => s.signOut);
  const [emailNotifications, setEmailNotifications] = useState(
    user?.email_notifications_enabled ?? true,
  );
  const soundEffectsEnabled = useSoundEffectsStore((s) => s.enabled);
  const setSoundEffectsEnabled = useSoundEffectsStore((s) => s.setEnabled);
  const [version, setVersion] = useState<string>();
  const [avatarOpen, setAvatarOpen] = useState(false);

  useEffect(() => {
    platform.app.getVersion().then(setVersion);
  }, []);

  const handleToggleEmailNotifications = async (checked: boolean) => {
    setEmailNotifications(checked);
    useAuthStore.setState((state) => ({
      user: state.user
        ? { ...state.user, email_notifications_enabled: checked }
        : null,
    }));
    try {
      await apiClient.updateSettings({ email_notifications_enabled: checked });
    } catch (err) {
      setEmailNotifications(!checked);
      useAuthStore.setState((state) => ({
        user: state.user
          ? { ...state.user, email_notifications_enabled: !checked }
          : null,
      }));
      toast.error(toUserMessage(err));
      logError(err, { scope: 'settings.emailNotifications' });
    }
  };

  const initials = user?.email_prefix?.slice(0, 2).toUpperCase() ?? '?';

  return (
    <div className="flex h-screen flex-col">
      <div className="drag-region flex items-center gap-3 border-b px-3 py-1">
        <WindowControls />
        <Button
          variant="ghost"
          size="sm"
          className="no-drag text-muted-foreground"
          onClick={() => navigate(-1)}
        >
          <ArrowLeft className="size-3.5" />
        </Button>
        <span className="text-sm font-medium">Settings</span>
        <div className="flex-1" />
      </div>

      <ScrollArea className="flex-1">
        {/* Profile header */}
        <div className="flex items-center gap-3 px-4 py-5">
          <button
            type="button"
            onClick={() => setAvatarOpen(true)}
            className="group relative rounded-full"
            aria-label="Change profile picture"
          >
            <HumanAvatar
              className="size-16"
              avatarObjectId={user?.avatar_object_id}
              initials={initials}
              fallbackClassName="bg-primary/10 text-primary text-xl font-medium"
            />
            <span className="bg-scrim/40 absolute inset-0 flex items-center justify-center rounded-full opacity-0 transition-opacity group-hover:opacity-100" />
            <span className="bg-primary text-primary-foreground ring-background absolute bottom-0 right-0 flex size-5 items-center justify-center rounded-full ring-2">
              <Camera className="size-2.5" />
            </span>
          </button>
          <div className="min-w-0 flex-1">
            <p className="truncate text-sm font-medium">{user?.email_prefix}</p>
            <Muted className="text-xs">{user?.email}</Muted>
          </div>
        </div>

        <AvatarEditDialog open={avatarOpen} onOpenChange={setAvatarOpen} />

        <Separator />

        <SettingsGroup title="Appearance">
          <ThemeSetting />
        </SettingsGroup>

        <Separator className="mt-4" />

        <SettingsGroup title="Notifications">
          <div className="flex w-full items-center gap-3 px-4 py-3">
            <span className="text-muted-foreground flex size-5 items-center justify-center">
              <Mail className="size-4" />
            </span>
            <span className="min-w-0 flex-1 text-sm font-medium">
              Email notifications
            </span>
            <Switch
              size="sm"
              checked={emailNotifications}
              onCheckedChange={handleToggleEmailNotifications}
            />
          </div>
          <div className="flex w-full items-center gap-3 px-4 py-3">
            <span className="text-muted-foreground flex size-5 items-center justify-center">
              <Volume2 className="size-4" />
            </span>
            <span className="min-w-0 flex-1 text-sm font-medium">
              Sound effects
            </span>
            <Switch
              size="sm"
              checked={soundEffectsEnabled}
              onCheckedChange={setSoundEffectsEnabled}
            />
          </div>
        </SettingsGroup>

        <Separator className="mt-4" />

        <SettingsGroup title="Media">
          <SettingsRow
            icon={<Mic className="size-4" />}
            label="Audio & Video"
            onClick={() => navigate('/settings/audio-video')}
          />
        </SettingsGroup>

        <Separator className="mt-4" />

        <SettingsGroup title="About">
          <SettingsRow
            icon={<Info className="size-4" />}
            label="Version"
            detail={version}
          />
        </SettingsGroup>

        <Separator className="mt-4" />

        <SettingsGroup title="Legal">
          <SettingsRow
            icon={<Shield className="size-4" />}
            label="Privacy Policy"
            onClick={() => platform.link.openExternal(PRIVACY_URL)}
          />
          <SettingsRow
            icon={<FileText className="size-4" />}
            label="Terms of Service"
            onClick={() => platform.link.openExternal(TERMS_URL)}
          />
        </SettingsGroup>

        <Separator className="mt-4" />

        <SettingsGroup title="Contact us">
          <div className="flex w-full items-center gap-3 px-4 py-3">
            <span className="text-muted-foreground flex size-5 items-center justify-center">
              <LifeBuoy className="size-4" />
            </span>
            <div className="min-w-0 flex-1">
              <p className="text-sm font-medium">Email support</p>
              <Muted className="text-xs">
                Questions, feedback, or bug reports
              </Muted>
            </div>
            <CopyableEmail email={SUPPORT_EMAIL} />
          </div>
        </SettingsGroup>

        <Separator className="mt-4" />

        <div className="py-4">
          <SettingsRow
            icon={<LogOut className="size-4" />}
            label="Sign out"
            onClick={signOut}
            destructive
          />
        </div>
      </ScrollArea>
    </div>
  );
}
