import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { LogOut, Unlink, AlertTriangle } from 'lucide-react';
import { trpc } from '@/lib/trpc';
import { useNotify } from '@/hooks/useNotify';
import { usePlatform } from '@/lib/platform';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { SettingsCard } from './SettingsCard';

export function AccountSection() {
  const { t } = useTranslation();
  const platform = usePlatform();
  const authStatusQuery = trpc.auth.status.useQuery(undefined, { staleTime: 5 * 60 * 1000 });
  const deviceIdQuery = trpc.settings.deviceId.useQuery(undefined, { enabled: platform.isElectron });
  const oauthAccountsQuery = trpc.auth.listOAuthAccounts.useQuery();
  const logoutMutation = trpc.auth.logout.useMutation();
  const changePasswordMutation = trpc.auth.changePassword.useMutation();
  const unlinkOAuthMutation = trpc.auth.unlinkOAuthAccount.useMutation();
  const deleteAccountMutation = trpc.auth.deleteAccount.useMutation();
  const utils = trpc.useUtils();

  const { notify, notifyError } = useNotify();
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');

  const profile = authStatusQuery.data?.profile;
  const hasPassword = profile?.hasPassword ?? true;

  function handleLogout() {
    logoutMutation.mutate(undefined, {
      onSuccess: () => {
        notify('info', 'toast.auth.loggedOut');
        void utils.auth.status.invalidate();
      },
    });
  }

  function handleChangePassword() {
    if (newPassword !== confirmPassword) {
      notify('error', 'settings.passwordMismatch');
      return;
    }
    changePasswordMutation.mutate(
      { currentPassword, newPassword },
      {
        onSuccess: () => {
          notify('success', 'settings.passwordChanged');
          setCurrentPassword('');
          setNewPassword('');
          setConfirmPassword('');
        },
        onError: (err) => notifyError('settings.passwordChangeError', err),
      },
    );
  }

  function handleUnlinkOAuth(provider: string) {
    unlinkOAuthMutation.mutate({ provider }, {
      onSuccess: () => {
        notify('success', 'settings.oauthUnlinked');
        void oauthAccountsQuery.refetch();
      },
      onError: (err) => notifyError('settings.oauthUnlinkError', err),
    });
  }

  function handleDeleteAccount() {
    deleteAccountMutation.mutate(undefined, {
      onSuccess: () => {
        notify('info', 'settings.accountDeleted');
        void utils.auth.status.invalidate();
      },
      onError: (err) => notifyError('settings.accountDeleteError', err),
    });
  }

  return (
    <>
      {/* Sign out */}
      <div className="flex items-center justify-between">
        <div>
          <p className="text-sm font-medium">{profile?.email}</p>
          <p className="text-xs text-muted-foreground capitalize">{profile?.tier} {t('settings.plan')}</p>
        </div>
        <Button
          variant="outline"
          size="sm"
          onClick={handleLogout}
          disabled={logoutMutation.isPending}
        >
          <LogOut data-icon="inline-start" />
          {t('settings.signOut')}
        </Button>
      </div>

      <Separator />

      {/* Password change — only for email/password users */}
      {hasPassword && (
        <SettingsCard
          title={t('settings.changePassword')}
          description={t('settings.changePasswordDescription')}
        >
          <div className="flex flex-col gap-3">
            <div className="flex flex-col gap-1.5">
              <Label htmlFor="currentPassword" className="text-xs">{t('settings.currentPassword')}</Label>
              <Input
                id="currentPassword"
                type="password"
                value={currentPassword}
                onChange={(e) => setCurrentPassword(e.target.value)}
                autoComplete="current-password"
              />
            </div>
            <div className="flex flex-col gap-1.5">
              <Label htmlFor="newPassword" className="text-xs">{t('settings.newPassword')}</Label>
              <Input
                id="newPassword"
                type="password"
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
                autoComplete="new-password"
              />
            </div>
            <div className="flex flex-col gap-1.5">
              <Label htmlFor="confirmPassword" className="text-xs">{t('settings.confirmPassword')}</Label>
              <Input
                id="confirmPassword"
                type="password"
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                autoComplete="new-password"
              />
            </div>
            <Button
              size="sm"
              className="w-fit"
              onClick={handleChangePassword}
              disabled={changePasswordMutation.isPending || !currentPassword || !newPassword || newPassword.length < 8}
            >
              {t('settings.updatePassword')}
            </Button>
          </div>
        </SettingsCard>
      )}

      {/* Connected accounts */}
      <SettingsCard
        title={t('settings.connectedAccounts')}
        description={t('settings.connectedAccountsDescription')}
      >
        <div className="flex flex-col gap-3">
          {oauthAccountsQuery.data?.map((account) => (
            <div key={account.provider} className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Badge variant="outline" className="capitalize">{account.provider}</Badge>
                {account.providerEmail && (
                  <span className="text-sm text-muted-foreground">{account.providerEmail}</span>
                )}
              </div>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handleUnlinkOAuth(account.provider)}
                disabled={unlinkOAuthMutation.isPending}
              >
                <Unlink data-icon="inline-start" />
                {t('settings.disconnect')}
              </Button>
            </div>
          ))}
          {(!oauthAccountsQuery.data || oauthAccountsQuery.data.length === 0) && (
            <p className="text-sm text-muted-foreground">{t('settings.noConnectedAccounts')}</p>
          )}
        </div>
      </SettingsCard>

      {/* Device ID — Electron only */}
      {platform.isElectron && (
        <SettingsCard title={t('settings.deviceId')} description={t('settings.deviceIdDescription')}>
          <p className="font-mono text-xs text-muted-foreground select-all">
            {deviceIdQuery.data ?? '—'}
          </p>
        </SettingsCard>
      )}

      <Separator />

      {/* Danger zone — delete account */}
      <SettingsCard title={t('settings.dangerZone')}>
        <div className="flex items-center justify-between">
          <div>
            <p className="text-sm font-medium text-destructive">{t('settings.deleteAccount')}</p>
            <p className="text-xs text-muted-foreground">{t('settings.deleteAccountDescription')}</p>
          </div>
          <AlertDialog>
            <AlertDialogTrigger asChild>
              <Button variant="outline" size="sm" className="text-destructive border-destructive/30 hover:bg-destructive/10">
                <AlertTriangle data-icon="inline-start" />
                {t('settings.deleteAccount')}
              </Button>
            </AlertDialogTrigger>
            <AlertDialogContent>
              <AlertDialogHeader>
                <AlertDialogTitle>{t('settings.deleteAccountConfirmTitle')}</AlertDialogTitle>
                <AlertDialogDescription>{t('settings.deleteAccountConfirmDescription')}</AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel>{t('common.cancel')}</AlertDialogCancel>
                <AlertDialogAction
                  onClick={handleDeleteAccount}
                  className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                >
                  {t('settings.deleteAccount')}
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>
        </div>
      </SettingsCard>
    </>
  );
}
