'use client';

import type { EscalationAction, EscalationRuleDashboard, ModerationDashboard } from '@nexumi/shared';
import { Plus, Trash2 } from 'lucide-react';
import { useId } 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 { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import type { SettingsSaveResult } from '@/components/settings/settings-form';
import { SettingsForm } from '@/components/settings/settings-form';

const ESCALATION_ACTIONS: EscalationAction[] = ['TIMEOUT', 'KICK', 'BAN'];

interface LocalEscalation extends EscalationRuleDashboard {
  clientKey: string;
}

function toLocal(rules: EscalationRuleDashboard[]): LocalEscalation[] {
  return rules.map((rule, index) => ({ ...rule, clientKey: rule.id ?? `existing-${index}` }));
}

function toRemote(rules: LocalEscalation[]): EscalationRuleDashboard[] {
  return rules.map(({ clientKey: _clientKey, ...rest }) => rest);
}

async function saveModeration(guildId: string, value: ModerationDashboard): Promise<SettingsSaveResult> {
  try {
    const response = await fetch(`/api/guilds/${guildId}/moderation`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(value)
    });
    if (!response.ok) {
      const body = (await response.json().catch(() => null)) as { error?: string } | null;
      return { ok: false, error: body?.error ?? `Request failed with status ${response.status}` };
    }
    return { ok: true };
  } catch {
    return { ok: false, error: 'Network error' };
  }
}

function EscalationRow({
  rule,
  onChange,
  onRemove
}: {
  rule: LocalEscalation;
  onChange: (rule: LocalEscalation) => void;
  onRemove: () => void;
}) {
  const t = useTranslations();
  const warnCountId = useId();
  const durationId = useId();
  const reasonId = useId();

  return (
    <div className="space-y-4 rounded-md border border-border p-4">
      <div className="flex flex-wrap items-end gap-4">
        <div className="space-y-2">
          <Label htmlFor={warnCountId}>{t('modulePages.moderation.warnCount')}</Label>
          <Input
            id={warnCountId}
            type="number"
            min={1}
            className="w-28"
            value={rule.warnCount}
            onChange={(event) => onChange({ ...rule, warnCount: Number(event.target.value) || 1 })}
          />
        </div>

        <div className="space-y-2">
          <Label>{t('modulePages.moderation.action')}</Label>
          <Select
            value={rule.action}
            onValueChange={(action) => onChange({ ...rule, action: action as EscalationAction })}
          >
            <SelectTrigger className="w-40">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {ESCALATION_ACTIONS.map((action) => (
                <SelectItem key={action} value={action}>
                  {t(`modulePages.moderation.actions.${action}`)}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {rule.action === 'TIMEOUT' && (
          <div className="space-y-2">
            <Label htmlFor={durationId}>{t('modulePages.moderation.durationMs')}</Label>
            <Input
              id={durationId}
              type="number"
              min={1000}
              step={1000}
              className="w-36"
              value={rule.durationMs ?? 0}
              onChange={(event) => onChange({ ...rule, durationMs: Number(event.target.value) || null })}
            />
          </div>
        )}

        <div className="flex items-center gap-2 pb-1">
          <Switch checked={rule.enabled} onCheckedChange={(enabled) => onChange({ ...rule, enabled })} />
          <span className="text-sm text-muted-foreground">{t('common.enabled')}</span>
        </div>

        <Button
          type="button"
          variant="ghost"
          size="icon"
          className="ml-auto"
          onClick={onRemove}
          aria-label={t('common.remove')}
        >
          <Trash2 className="size-4" />
        </Button>
      </div>

      <div className="space-y-2">
        <Label htmlFor={reasonId}>{t('modulePages.moderation.reason')}</Label>
        <Input
          id={reasonId}
          value={rule.reason ?? ''}
          onChange={(event) => onChange({ ...rule, reason: event.target.value || null })}
          placeholder={t('modulePages.moderation.reasonPlaceholder')}
        />
      </div>
    </div>
  );
}

interface ModerationFormProps {
  guildId: string;
  initialValue: ModerationDashboard;
}

export function ModerationForm({ guildId, initialValue }: ModerationFormProps) {
  const t = useTranslations();

  return (
    <SettingsForm<{ moderationEnabled: boolean; escalations: LocalEscalation[] }>
      initialValue={{ moderationEnabled: initialValue.moderationEnabled, escalations: toLocal(initialValue.escalations) }}
      onSave={(value) =>
        saveModeration(guildId, { moderationEnabled: value.moderationEnabled, escalations: toRemote(value.escalations) })
      }
    >
      {({ value, setValue }) => (
        <div className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>{t('modulePages.moderation.title')}</CardTitle>
              <CardDescription>{t('modulePages.moderation.description')}</CardDescription>
            </CardHeader>
            <CardContent>
              <FieldAnchor id="field-mod-enabled">
                <div className="flex items-center justify-between rounded-md border border-border p-4">
                  <div className="space-y-0.5">
                    <Label>{t('modulePages.moderation.enabledLabel')}</Label>
                    <p className="text-sm text-muted-foreground">{t('modulePages.moderation.enabledHint')}</p>
                  </div>
                  <Switch
                    checked={value.moderationEnabled}
                    onCheckedChange={(checked) => setValue((prev) => ({ ...prev, moderationEnabled: checked }))}
                  />
                </div>
              </FieldAnchor>
            </CardContent>
          </Card>

          <FieldAnchor id="field-mod-escalations">
            <Card>
              <CardHeader>
                <CardTitle>{t('modulePages.moderation.escalationsTitle')}</CardTitle>
                <CardDescription>{t('modulePages.moderation.escalationsDescription')}</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                {value.escalations.length === 0 && (
                  <p className="text-sm text-muted-foreground">{t('modulePages.moderation.noEscalations')}</p>
                )}
                {value.escalations.map((rule) => (
                  <EscalationRow
                    key={rule.clientKey}
                    rule={rule}
                    onChange={(updated) =>
                      setValue((prev) => ({
                        ...prev,
                        escalations: prev.escalations.map((entry) => (entry.clientKey === rule.clientKey ? updated : entry))
                      }))
                    }
                    onRemove={() =>
                      setValue((prev) => ({
                        ...prev,
                        escalations: prev.escalations.filter((entry) => entry.clientKey !== rule.clientKey)
                      }))
                    }
                  />
                ))}
                <Button
                  type="button"
                  variant="outline"
                  onClick={() =>
                    setValue((prev) => ({
                      ...prev,
                      escalations: [
                        ...prev.escalations,
                        {
                          clientKey: `new-${Date.now()}-${prev.escalations.length}`,
                          warnCount: prev.escalations.length + 1,
                          action: 'TIMEOUT',
                          durationMs: 3_600_000,
                          reason: null,
                          enabled: true
                        }
                      ]
                    }))
                  }
                >
                  <Plus className="size-4" />
                  {t('modulePages.moderation.addEscalation')}
                </Button>
              </CardContent>
            </Card>
          </FieldAnchor>
        </div>
      )}
    </SettingsForm>
  );
}
