'use client';

import type { SuggestionAction, SuggestionDashboard } from '@nexumi/shared';
import { useState } from 'react';
import { toast } from 'sonner';
import { FieldAnchor } from '@/components/layout/field-anchor';
import { useTranslations } from '@/components/locale-provider';
import { Badge, type BadgeProps } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';

const STATUS_VARIANTS: Record<SuggestionDashboard['status'], BadgeProps['variant']> = {
  OPEN: 'secondary',
  APPROVED: 'success',
  DENIED: 'destructive',
  CONSIDERED: 'outline',
  IMPLEMENTED: 'success'
};

const STATUS_FILTERS: Array<SuggestionDashboard['status'] | 'ALL'> = [
  'ALL',
  'OPEN',
  'APPROVED',
  'DENIED',
  'CONSIDERED',
  'IMPLEMENTED'
];

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

interface SuggestionsListManagerProps {
  guildId: string;
  initialSuggestions: SuggestionDashboard[];
}

export function SuggestionsListManager({ guildId, initialSuggestions }: SuggestionsListManagerProps) {
  const t = useTranslations();
  const [suggestions, setSuggestions] = useState<SuggestionDashboard[]>(initialSuggestions);
  const [statusFilter, setStatusFilter] = useState<SuggestionDashboard['status'] | 'ALL'>('ALL');
  const [reasons, setReasons] = useState<Record<string, string>>({});
  const [pendingId, setPendingId] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function reload(nextStatus: SuggestionDashboard['status'] | 'ALL') {
    setStatusFilter(nextStatus);
    setLoading(true);
    try {
      const query = nextStatus === 'ALL' ? '' : `?status=${nextStatus}`;
      const response = await fetch(`/api/guilds/${guildId}/suggestions/items${query}`);
      const body = (await response.json().catch(() => null)) as { suggestions?: SuggestionDashboard[] } | null;
      if (response.ok && body?.suggestions) {
        setSuggestions(body.suggestions);
      }
    } finally {
      setLoading(false);
    }
  }

  async function handleAction(suggestion: SuggestionDashboard, status: SuggestionAction['status']) {
    setPendingId(suggestion.id);
    try {
      const response = await fetch(`/api/guilds/${guildId}/suggestions/items/${suggestion.id}/action`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status, staffReason: reasons[suggestion.id] || null })
      });
      const body = (await response.json().catch(() => null)) as (SuggestionDashboard & { error?: string }) | null;
      if (!response.ok || !body) {
        toast.error(body?.error ?? t('common.saveError'));
        return;
      }
      setSuggestions((prev) => prev.map((entry) => (entry.id === suggestion.id ? body : entry)));
      toast.success(t('common.saveSuccess'));
    } catch {
      toast.error(t('common.saveError'));
    } finally {
      setPendingId(null);
    }
  }

  return (
    <FieldAnchor id="field-suggestions-list">
    <Card>
      <CardHeader className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <CardTitle>{t('modulePages.suggestions.listTitle')}</CardTitle>
          <CardDescription>{t('modulePages.suggestions.listDescription')}</CardDescription>
        </div>
        <Select value={statusFilter} onValueChange={(status) => reload(status as SuggestionDashboard['status'] | 'ALL')}>
          <SelectTrigger className="w-full sm:w-48">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {STATUS_FILTERS.map((status) => (
              <SelectItem key={status} value={status}>
                {status === 'ALL' ? t('modulePages.suggestions.statusAll') : t(`modulePages.suggestions.status.${status}`)}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </CardHeader>
      <CardContent className="space-y-3">
        {loading && <p className="text-sm text-muted-foreground">{t('common.loading')}</p>}
        {!loading && suggestions.length === 0 && (
          <p className="text-sm text-muted-foreground">{t('modulePages.suggestions.empty')}</p>
        )}
        {!loading &&
          suggestions.map((suggestion) => (
            <div key={suggestion.id} className="space-y-3 rounded-md border border-border p-4">
              <div className="flex flex-wrap items-start justify-between gap-2">
                <div>
                  <p className="font-medium">{suggestion.content}</p>
                  <p className="text-xs text-muted-foreground">
                    &lt;@{suggestion.authorId}&gt; · 👍 {suggestion.upvotes} · 👎 {suggestion.downvotes} ·{' '}
                    {formatDate(suggestion.createdAt)}
                  </p>
                </div>
                <Badge variant={STATUS_VARIANTS[suggestion.status]}>
                  {t(`modulePages.suggestions.status.${suggestion.status}`)}
                </Badge>
              </div>
              {suggestion.staffReason && (
                <p className="text-xs text-muted-foreground">
                  {t('modulePages.suggestions.staffReason')}: {suggestion.staffReason}
                </p>
              )}
              <Textarea
                value={reasons[suggestion.id] ?? ''}
                onChange={(event) => setReasons((prev) => ({ ...prev, [suggestion.id]: event.target.value }))}
                placeholder={t('modulePages.suggestions.reasonPlaceholder')}
                rows={2}
              />
              <div className="flex flex-wrap gap-2">
                <Button
                  type="button"
                  size="sm"
                  variant="outline"
                  disabled={pendingId === suggestion.id}
                  onClick={() => handleAction(suggestion, 'APPROVED')}
                >
                  {t('modulePages.suggestions.approve')}
                </Button>
                <Button
                  type="button"
                  size="sm"
                  variant="outline"
                  disabled={pendingId === suggestion.id}
                  onClick={() => handleAction(suggestion, 'DENIED')}
                >
                  {t('modulePages.suggestions.deny')}
                </Button>
                <Button
                  type="button"
                  size="sm"
                  variant="outline"
                  disabled={pendingId === suggestion.id}
                  onClick={() => handleAction(suggestion, 'CONSIDERED')}
                >
                  {t('modulePages.suggestions.consider')}
                </Button>
                <Button
                  type="button"
                  size="sm"
                  variant="outline"
                  disabled={pendingId === suggestion.id}
                  onClick={() => handleAction(suggestion, 'IMPLEMENTED')}
                >
                  {t('modulePages.suggestions.implement')}
                </Button>
              </div>
            </div>
          ))}
      </CardContent>
    </Card>
    </FieldAnchor>
  );
}
