'use client';

import type { WarningDashboard } from '@nexumi/shared';
import { Search, Trash2 } from 'lucide-react';
import { useCallback, useState } from 'react';
import { FieldAnchor } from '@/components/layout/field-anchor';
import { useTranslations } from '@/components/locale-provider';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';

interface WarningsTableProps {
  guildId: string;
  initialWarnings: WarningDashboard[];
}

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

export function WarningsTable({ guildId, initialWarnings }: WarningsTableProps) {
  const t = useTranslations();
  const [warnings, setWarnings] = useState<WarningDashboard[]>(initialWarnings);
  const [userId, setUserId] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchWarnings = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const params = new URLSearchParams();
      if (userId.trim()) params.set('userId', userId.trim());
      const response = await fetch(`/api/guilds/${guildId}/warnings?${params.toString()}`);
      if (!response.ok) {
        setError(t('common.saveError'));
        return;
      }
      const body = (await response.json()) as { warnings: WarningDashboard[] };
      setWarnings(body.warnings);
    } catch {
      setError(t('common.saveError'));
    } finally {
      setLoading(false);
    }
  }, [guildId, t, userId]);

  async function removeWarning(warningId: string) {
    if (!window.confirm(t('modulePages.moderation.confirmRemoveWarning'))) {
      return;
    }
    setError(null);
    const response = await fetch(
      `/api/guilds/${guildId}/warnings?id=${encodeURIComponent(warningId)}`,
      { method: 'DELETE' }
    );
    if (!response.ok) {
      setError(t('common.saveError'));
      return;
    }
    setWarnings((prev) => prev.filter((entry) => entry.id !== warningId));
  }

  return (
    <FieldAnchor id="field-mod-warnings">
      <Card>
        <CardHeader>
          <CardTitle>{t('modulePages.moderation.warningsTitle')}</CardTitle>
          <CardDescription>{t('modulePages.moderation.warningsDescription')}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <form
            className="flex flex-wrap items-end gap-3"
            onSubmit={(event) => {
              event.preventDefault();
              void fetchWarnings();
            }}
          >
            <div className="flex-1 space-y-2">
              <Input
                value={userId}
                onChange={(event) => setUserId(event.target.value)}
                placeholder={t('modulePages.moderation.warningsSearchUser')}
              />
            </div>
            <Button type="submit" variant="outline" disabled={loading}>
              <Search className="size-4" />
              {t('common.confirm')}
            </Button>
          </form>

          {error && <p className="text-sm text-destructive">{error}</p>}

          {loading ? (
            <div className="space-y-2">
              {Array.from({ length: 3 }).map((_, index) => (
                <Skeleton key={index} className="h-12 rounded-md" />
              ))}
            </div>
          ) : warnings.length === 0 ? (
            <p className="text-sm text-muted-foreground">{t('modulePages.moderation.warningsEmpty')}</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-border text-left text-xs uppercase text-muted-foreground">
                    <th className="py-2 pr-4">{t('modulePages.moderation.target')}</th>
                    <th className="py-2 pr-4">{t('modulePages.moderation.moderator')}</th>
                    <th className="py-2 pr-4">{t('modulePages.moderation.reason')}</th>
                    <th className="py-2 pr-4">{t('modulePages.moderation.createdAt')}</th>
                    <th className="py-2 pr-4" />
                  </tr>
                </thead>
                <tbody className="divide-y divide-border">
                  {warnings.map((entry) => (
                    <tr key={entry.id}>
                      <td className="py-2 pr-4 font-mono text-xs">{entry.userId}</td>
                      <td className="py-2 pr-4 font-mono text-xs">{entry.moderatorId}</td>
                      <td className="max-w-64 truncate py-2 pr-4">
                        {entry.reason ?? t('modulePages.moderation.noReason')}
                      </td>
                      <td className="whitespace-nowrap py-2 pr-4 text-xs text-muted-foreground">
                        {formatDate(entry.createdAt)}
                      </td>
                      <td className="py-2 pr-4">
                        <Button
                          type="button"
                          variant="ghost"
                          size="icon"
                          aria-label={t('modulePages.moderation.removeWarning')}
                          onClick={() => void removeWarning(entry.id)}
                        >
                          <Trash2 className="size-4" />
                        </Button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>
    </FieldAnchor>
  );
}
