import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  ChevronRight,
  LogOut,
  Info,
  Shield,
  Mail,
  Mic,
  LifeBuoy,
  FileText,
  Volume2,
  ArrowLeft,
} from 'lucide-react';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Separator } from '@/components/ui/separator';
import { Switch } from '@/components/ui/switch';
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 { 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>
  );
}

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>();

  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">
          <Avatar size="lg">
            <AvatarFallback className="bg-primary/10 text-primary font-medium">
              {initials}
            </AvatarFallback>
          </Avatar>
          <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>

        <Separator />

        <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>
  );
}
