'use client';

import type { GuildBackupDashboard } from '@nexumi/shared';
import { Download, Info, Plus, RotateCcw, Trash2 } from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';
import { FieldAnchor } from '@/components/layout/field-anchor';
import { useTranslations } from '@/components/locale-provider';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

function formatDate(iso: string): string {
  return new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
}

interface GuildBackupManagerProps {
  guildId: string;
  initialBackups: GuildBackupDashboard[];
  isOwner: boolean;
}

export function GuildBackupManager({ guildId, initialBackups, isOwner }: GuildBackupManagerProps) {
  const t = useTranslations();
  const [backups, setBackups] = useState<GuildBackupDashboard[]>(initialBackups);
  const [name, setName] = useState('');
  const [creating, setCreating] = useState(false);
  const [pendingId, setPendingId] = useState<string | null>(null);
  const [infoId, setInfoId] = useState<string | null>(null);
  const [infoText, setInfoText] = useState<string | null>(null);

  async function handleCreate() {
    if (!name.trim()) {
      toast.error(t('modulePages.guildbackup.nameRequired'));
      return;
    }
    setCreating(true);
    try {
      const response = await fetch(`/api/guilds/${guildId}/guildbackup`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: name.trim() })
      });
      const body = (await response.json().catch(() => null)) as (GuildBackupDashboard & { error?: string }) | null;
      if (!response.ok || !body) {
        toast.error(body?.error ?? t('common.saveError'));
        return;
      }
      setBackups((prev) => [body, ...prev]);
      setName('');
      toast.success(t('modulePages.guildbackup.created'));
    } catch {
      toast.error(t('common.saveError'));
    } finally {
      setCreating(false);
    }
  }

  async function handleInfo(backup: GuildBackupDashboard) {
    if (infoId === backup.id) {
      setInfoId(null);
      setInfoText(null);
      return;
    }
    setInfoId(backup.id);
    try {
      const response = await fetch(`/api/guilds/${guildId}/guildbackup/${backup.id}`);
      const body = (await response.json().catch(() => null)) as {
        payload?: { guildName: string; roles: unknown[]; channels: unknown[] } | null;
        error?: string;
      } | null;
      if (!response.ok || !body?.payload) {
        setInfoText(t('modulePages.guildbackup.infoUnavailable'));
        return;
      }
      setInfoText(
        `${t('modulePages.guildbackup.infoGuildName')}: ${body.payload.guildName} · ${t('modulePages.guildbackup.infoRoles')}: ${body.payload.roles.length} · ${t('modulePages.guildbackup.infoChannels')}: ${body.payload.channels.length}`
      );
    } catch {
      setInfoText(t('modulePages.guildbackup.infoUnavailable'));
    }
  }

  function handleDownload(backup: GuildBackupDashboard) {
    window.open(`/api/guilds/${guildId}/guildbackup/${backup.id}/download`, '_blank');
  }

  async function handleDelete(backup: GuildBackupDashboard) {
    if (!window.confirm(t('modulePages.guildbackup.confirmDelete'))) {
      return;
    }
    setPendingId(backup.id);
    try {
      const response = await fetch(`/api/guilds/${guildId}/guildbackup/${backup.id}`, { method: 'DELETE' });
      if (!response.ok) {
        toast.error(t('common.saveError'));
        return;
      }
      setBackups((prev) => prev.filter((entry) => entry.id !== backup.id));
      toast.success(t('common.saveSuccess'));
    } catch {
      toast.error(t('common.saveError'));
    } finally {
      setPendingId(null);
    }
  }

  async function handleRestore(backup: GuildBackupDashboard) {
    if (!window.confirm(t('modulePages.guildbackup.confirmRestoreStep1'))) {
      return;
    }
    if (!window.confirm(t('modulePages.guildbackup.confirmRestoreStep2'))) {
      return;
    }
    setPendingId(backup.id);
    try {
      const response = await fetch(`/api/guilds/${guildId}/guildbackup/${backup.id}/restore`, { method: 'POST' });
      const body = (await response.json().catch(() => null)) as { error?: string } | null;
      if (!response.ok) {
        toast.error(body?.error ?? t('common.saveError'));
        return;
      }
      toast.success(t('modulePages.guildbackup.restoreQueued'));
    } catch {
      toast.error(t('common.saveError'));
    } finally {
      setPendingId(null);
    }
  }

  return (
    <FieldAnchor id="field-backup">
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>{t('modulePages.guildbackup.createTitle')}</CardTitle>
          <CardDescription>{t('modulePages.guildbackup.createDescription')}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label>{t('modulePages.guildbackup.name')}</Label>
            <Input value={name} onChange={(event) => setName(event.target.value)} placeholder={t('modulePages.guildbackup.namePlaceholder')} />
          </div>
          <Button type="button" onClick={handleCreate} disabled={creating}>
            <Plus className="size-4" />
            {creating ? t('common.saving') : t('modulePages.guildbackup.create')}
          </Button>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>{t('modulePages.guildbackup.listTitle')}</CardTitle>
          <CardDescription>{t('modulePages.guildbackup.listDescription')}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          {backups.length === 0 && (
            <p className="text-sm text-muted-foreground">{t('modulePages.guildbackup.empty')}</p>
          )}
          {backups.map((backup) => (
            <div key={backup.id} className="space-y-2 rounded-md border border-border p-4">
              <div className="flex flex-wrap items-start justify-between gap-2">
                <div>
                  <p className="font-medium">{backup.name}</p>
                  <p className="text-xs text-muted-foreground">
                    {formatDate(backup.createdAt)} · {t('modulePages.guildbackup.infoRoles')}: {backup.roleCount} ·{' '}
                    {t('modulePages.guildbackup.infoChannels')}: {backup.channelCount}
                  </p>
                </div>
                {!isOwner && (
                  <Badge variant="outline">{t('modulePages.guildbackup.ownerOnlyBadge')}</Badge>
                )}
              </div>
              {infoId === backup.id && infoText && (
                <p className="rounded-md bg-muted p-2 text-xs text-muted-foreground">{infoText}</p>
              )}
              <div className="flex flex-wrap gap-2">
                <Button type="button" size="sm" variant="outline" onClick={() => handleInfo(backup)}>
                  <Info className="size-4" />
                  {t('modulePages.guildbackup.info')}
                </Button>
                <Button type="button" size="sm" variant="outline" onClick={() => handleDownload(backup)}>
                  <Download className="size-4" />
                  {t('modulePages.guildbackup.download')}
                </Button>
                {isOwner && (
                  <Button
                    type="button"
                    size="sm"
                    variant="outline"
                    disabled={pendingId === backup.id}
                    onClick={() => handleRestore(backup)}
                  >
                    <RotateCcw className="size-4" />
                    {t('modulePages.guildbackup.restore')}
                  </Button>
                )}
                <Button
                  type="button"
                  size="sm"
                  variant="ghost"
                  disabled={pendingId === backup.id}
                  onClick={() => handleDelete(backup)}
                >
                  <Trash2 className="size-4" />
                  {t('common.remove')}
                </Button>
              </div>
            </div>
          ))}
        </CardContent>
      </Card>
    </div>
    </FieldAnchor>
  );
}
