'use client';

import type { CaseDashboard } from '@nexumi/shared';
import { Pencil, 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 CasesTableProps {
  guildId: string;
  initialCases: CaseDashboard[];
}

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

export function CasesTable({ guildId, initialCases }: CasesTableProps) {
  const t = useTranslations();
  const [cases, setCases] = useState<CaseDashboard[]>(initialCases);
  const [search, setSearch] = useState('');
  const [action, setAction] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editReason, setEditReason] = useState('');

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

  async function saveReason(caseId: string) {
    setError(null);
    const response = await fetch(`/api/guilds/${guildId}/cases`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ id: caseId, reason: editReason })
    });
    if (!response.ok) {
      setError(t('common.saveError'));
      return;
    }
    const body = (await response.json()) as { case: CaseDashboard };
    setCases((prev) => prev.map((entry) => (entry.id === caseId ? body.case : entry)));
    setEditingId(null);
  }

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

  return (
    <FieldAnchor id="field-mod-cases">
      <Card>
        <CardHeader>
          <CardTitle>{t('modulePages.moderation.casesTitle')}</CardTitle>
          <CardDescription>{t('modulePages.moderation.casesDescription')}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <form
            className="flex flex-wrap items-end gap-3"
            onSubmit={(event) => {
              event.preventDefault();
              void fetchCases();
            }}
          >
            <div className="flex-1 space-y-2">
              <Input
                value={search}
                onChange={(event) => setSearch(event.target.value)}
                placeholder={t('modulePages.moderation.searchPlaceholder')}
              />
            </div>
            <div className="space-y-2">
              <Input
                value={action}
                onChange={(event) => setAction(event.target.value)}
                placeholder={t('modulePages.moderation.actionPlaceholder')}
                className="w-40"
              />
            </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: 4 }).map((_, index) => (
                <Skeleton key={index} className="h-12 rounded-md" />
              ))}
            </div>
          ) : cases.length === 0 ? (
            <p className="text-sm text-muted-foreground">{t('modulePages.moderation.casesEmpty')}</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">#</th>
                    <th className="py-2 pr-4">{t('modulePages.moderation.action')}</th>
                    <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">
                  {cases.map((entry) => (
                    <tr key={entry.id}>
                      <td className="py-2 pr-4 font-mono text-xs">#{entry.caseNumber}</td>
                      <td className="py-2 pr-4">{entry.action}</td>
                      <td className="py-2 pr-4 font-mono text-xs">{entry.targetUserId}</td>
                      <td className="py-2 pr-4 font-mono text-xs">{entry.moderatorId}</td>
                      <td className="max-w-64 py-2 pr-4">
                        {editingId === entry.id ? (
                          <div className="flex items-center gap-2">
                            <Input
                              value={editReason}
                              onChange={(event) => setEditReason(event.target.value)}
                              aria-label={t('modulePages.moderation.editReason')}
                            />
                            <Button type="button" size="sm" onClick={() => void saveReason(entry.id)}>
                              {t('modulePages.moderation.saveReason')}
                            </Button>
                          </div>
                        ) : (
                          <span className="truncate block">
                            {entry.reason ?? t('modulePages.moderation.noReason')}
                          </span>
                        )}
                      </td>
                      <td className="whitespace-nowrap py-2 pr-4 text-xs text-muted-foreground">
                        {formatDate(entry.createdAt)}
                      </td>
                      <td className="py-2 pr-4">
                        <div className="flex gap-1">
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            aria-label={t('modulePages.moderation.editReason')}
                            onClick={() => {
                              setEditingId(entry.id);
                              setEditReason(entry.reason ?? '');
                            }}
                          >
                            <Pencil className="size-4" />
                          </Button>
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            aria-label={t('modulePages.moderation.deleteCase')}
                            onClick={() => void removeCase(entry.id)}
                          >
                            <Trash2 className="size-4" />
                          </Button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>
    </FieldAnchor>
  );
}
