'use client';

import type {
  AutoModAction,
  AutoModRuleType,
  AutomodConfigDashboard,
  AutomodRuleDashboard
} from '@nexumi/shared';
import { FieldAnchor } from '@/components/layout/field-anchor';
import { useTranslations } from '@/components/locale-provider';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { DiscordChannelMultiSelect } from '@/components/ui/discord-channel-select';
import { DiscordRoleMultiSelect } from '@/components/ui/discord-role-select';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { StringListEditor } from '@/components/ui/string-list-editor';
import { Switch } from '@/components/ui/switch';
import type { SettingsSaveResult } from '@/components/settings/settings-form';
import { SettingsForm } from '@/components/settings/settings-form';

const ACTIONS: AutoModAction[] = ['DELETE', 'WARN', 'TIMEOUT', 'KICK', 'BAN'];

async function saveAutomod(guildId: string, value: AutomodConfigDashboard): Promise<SettingsSaveResult> {
  try {
    const cleaned: AutomodConfigDashboard = {
      ...value,
      rules: value.rules.map((rule) => ({
        ...rule,
        durationMs: rule.action === 'TIMEOUT' ? rule.durationMs ?? 60_000 : null,
        threshold: {
          ...rule.threshold,
          linkWhitelist: (rule.threshold.linkWhitelist ?? []).map((s) => s.trim()).filter(Boolean),
          linkBlacklist: (rule.threshold.linkBlacklist ?? []).map((s) => s.trim()).filter(Boolean)
        },
        wordList: {
          words: (rule.wordList.words ?? []).map((s) => s.trim()).filter(Boolean),
          regexPatterns: (rule.wordList.regexPatterns ?? []).map((s) => s.trim()).filter(Boolean)
        }
      }))
    };
    const response = await fetch(`/api/guilds/${guildId}/automod`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(cleaned)
    });
    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 updateRule(
  rules: AutomodRuleDashboard[],
  ruleType: AutoModRuleType,
  patch: Partial<AutomodRuleDashboard>
): AutomodRuleDashboard[] {
  return rules.map((rule) => (rule.ruleType === ruleType ? { ...rule, ...patch } : rule));
}

function RuleCard({
  guildId,
  rule,
  onChange
}: {
  guildId: string;
  rule: AutomodRuleDashboard;
  onChange: (patch: Partial<AutomodRuleDashboard>) => void;
}) {
  const t = useTranslations();
  const type = rule.ruleType;

  return (
    <FieldAnchor id={`field-automod-rule-${type}`}>
      <Card>
        <CardHeader className="pb-3">
          <div className="flex items-start justify-between gap-4">
            <div>
              <CardTitle className="text-base">
                {t(`modulePages.automod.rules.${type}.title`)}
              </CardTitle>
              <CardDescription>{t(`modulePages.automod.rules.${type}.description`)}</CardDescription>
            </div>
            <Switch
              checked={rule.enabled}
              onCheckedChange={(enabled) => onChange({ enabled })}
              aria-label={t(`modulePages.automod.rules.${type}.title`)}
            />
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label>{t('modulePages.automod.ruleAction')}</Label>
              <Select
                value={rule.action}
                onValueChange={(action) => onChange({ action: action as AutoModAction })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {ACTIONS.map((action) => (
                    <SelectItem key={action} value={action}>
                      {t(`modulePages.automod.actions.${action}`)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            {rule.action === 'TIMEOUT' ? (
              <div className="space-y-2">
                <Label>{t('modulePages.automod.timeoutMinutes')}</Label>
                <Input
                  type="number"
                  min={1}
                  max={40320}
                  value={Math.max(1, Math.round((rule.durationMs ?? 60_000) / 60_000))}
                  onChange={(event) =>
                    onChange({
                      durationMs: Math.max(1, Number(event.target.value) || 1) * 60_000
                    })
                  }
                />
              </div>
            ) : null}
          </div>

          {type === 'SPAM' || type === 'DUPLICATE' ? (
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label>
                  {type === 'SPAM'
                    ? t('modulePages.automod.thresholds.maxMessages')
                    : t('modulePages.automod.thresholds.duplicateCount')}
                </Label>
                <Input
                  type="number"
                  min={1}
                  value={
                    type === 'SPAM'
                      ? (rule.threshold.maxMessages ?? 5)
                      : (rule.threshold.duplicateCount ?? 3)
                  }
                  onChange={(event) =>
                    onChange({
                      threshold: {
                        ...rule.threshold,
                        ...(type === 'SPAM'
                          ? { maxMessages: Number(event.target.value) || 1 }
                          : { duplicateCount: Number(event.target.value) || 1 })
                      }
                    })
                  }
                />
              </div>
              <div className="space-y-2">
                <Label>{t('modulePages.automod.thresholds.windowSeconds')}</Label>
                <Input
                  type="number"
                  min={1}
                  value={rule.threshold.windowSeconds ?? (type === 'SPAM' ? 5 : 30)}
                  onChange={(event) =>
                    onChange({
                      threshold: {
                        ...rule.threshold,
                        windowSeconds: Number(event.target.value) || 1
                      }
                    })
                  }
                />
              </div>
            </div>
          ) : null}

          {type === 'MASS_MENTION' ? (
            <div className="space-y-2">
              <Label>{t('modulePages.automod.thresholds.maxMentions')}</Label>
              <Input
                type="number"
                min={1}
                className="w-40"
                value={rule.threshold.maxMentions ?? 5}
                onChange={(event) =>
                  onChange({
                    threshold: { ...rule.threshold, maxMentions: Number(event.target.value) || 1 }
                  })
                }
              />
            </div>
          ) : null}

          {type === 'CAPS' ? (
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label>{t('modulePages.automod.thresholds.capsPercent')}</Label>
                <Input
                  type="number"
                  min={0}
                  max={100}
                  value={rule.threshold.capsPercent ?? 70}
                  onChange={(event) =>
                    onChange({
                      threshold: {
                        ...rule.threshold,
                        capsPercent: Number(event.target.value) || 0
                      }
                    })
                  }
                />
              </div>
              <div className="space-y-2">
                <Label>{t('modulePages.automod.thresholds.minLength')}</Label>
                <Input
                  type="number"
                  min={0}
                  value={rule.threshold.minLength ?? 10}
                  onChange={(event) =>
                    onChange({
                      threshold: {
                        ...rule.threshold,
                        minLength: Number(event.target.value) || 0
                      }
                    })
                  }
                />
              </div>
            </div>
          ) : null}

          {type === 'EMOJI_SPAM' ? (
            <div className="space-y-2">
              <Label>{t('modulePages.automod.thresholds.maxEmojis')}</Label>
              <Input
                type="number"
                min={1}
                className="w-40"
                value={rule.threshold.maxEmojis ?? 10}
                onChange={(event) =>
                  onChange({
                    threshold: { ...rule.threshold, maxEmojis: Number(event.target.value) || 1 }
                  })
                }
              />
            </div>
          ) : null}

          {type === 'EXTERNAL_LINK' ? (
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label>{t('modulePages.automod.linkWhitelist')}</Label>
                <StringListEditor
                  value={rule.threshold.linkWhitelist ?? []}
                  onChange={(linkWhitelist) =>
                    onChange({ threshold: { ...rule.threshold, linkWhitelist } })
                  }
                  placeholder="discord.com"
                  addLabel={t('modulePages.automod.addHost')}
                />
              </div>
              <div className="space-y-2">
                <Label>{t('modulePages.automod.linkBlacklist')}</Label>
                <StringListEditor
                  value={rule.threshold.linkBlacklist ?? []}
                  onChange={(linkBlacklist) =>
                    onChange({ threshold: { ...rule.threshold, linkBlacklist } })
                  }
                  placeholder="example.com"
                  addLabel={t('modulePages.automod.addHost')}
                />
              </div>
            </div>
          ) : null}

          {type === 'WORD_FILTER' ? (
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label>{t('modulePages.automod.wordList')}</Label>
                <StringListEditor
                  value={rule.wordList.words}
                  onChange={(words) => onChange({ wordList: { ...rule.wordList, words } })}
                  placeholder={t('modulePages.automod.wordPlaceholder')}
                  addLabel={t('modulePages.automod.addWord')}
                />
              </div>
              <div className="space-y-2">
                <Label>{t('modulePages.automod.regexList')}</Label>
                <StringListEditor
                  value={rule.wordList.regexPatterns}
                  onChange={(regexPatterns) =>
                    onChange({ wordList: { ...rule.wordList, regexPatterns } })
                  }
                  placeholder="\\bspam\\b"
                  addLabel={t('modulePages.automod.addRegex')}
                />
              </div>
            </div>
          ) : null}

          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label>{t('modulePages.automod.exceptionRoles')}</Label>
              <DiscordRoleMultiSelect
                guildId={guildId}
                value={rule.exceptions.roleIds}
                onChange={(roleIds) =>
                  onChange({ exceptions: { ...rule.exceptions, roleIds } })
                }
              />
            </div>
            <div className="space-y-2">
              <Label>{t('modulePages.automod.exceptionChannels')}</Label>
              <DiscordChannelMultiSelect
                guildId={guildId}
                value={rule.exceptions.channelIds}
                onChange={(channelIds) =>
                  onChange({ exceptions: { ...rule.exceptions, channelIds } })
                }
              />
            </div>
          </div>
        </CardContent>
      </Card>
    </FieldAnchor>
  );
}

interface AutomodFormProps {
  guildId: string;
  initialValue: AutomodConfigDashboard;
}

export function AutomodForm({ guildId, initialValue }: AutomodFormProps) {
  const t = useTranslations();

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

          <FieldAnchor id="field-automod-rules">
            <div className="space-y-4">
              <div>
                <h2 className="text-lg font-semibold">{t('modulePages.automod.rulesTitle')}</h2>
                <p className="text-sm text-muted-foreground">{t('modulePages.automod.rulesDescription')}</p>
              </div>
              {value.rules.map((rule) => (
                <RuleCard
                  key={rule.ruleType}
                  guildId={guildId}
                  rule={rule}
                  onChange={(patch) =>
                    setValue((prev) => ({
                      ...prev,
                      rules: updateRule(prev.rules, rule.ruleType, patch)
                    }))
                  }
                />
              ))}
            </div>
          </FieldAnchor>

          <FieldAnchor id="field-anti-raid">
            <Card>
              <CardHeader>
                <CardTitle>{t('modulePages.automod.antiRaidTitle')}</CardTitle>
                <CardDescription>{t('modulePages.automod.antiRaidDescription')}</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-center justify-between rounded-md border border-border p-4">
                  <Label>{t('modulePages.automod.antiRaidEnabled')}</Label>
                  <Switch
                    checked={value.antiRaidEnabled}
                    onCheckedChange={(checked) =>
                      setValue((prev) => ({ ...prev, antiRaidEnabled: checked }))
                    }
                  />
                </div>
                <div className="grid gap-4 sm:grid-cols-3">
                  <div className="space-y-2">
                    <Label>{t('modulePages.automod.antiRaidJoinThreshold')}</Label>
                    <Input
                      type="number"
                      min={1}
                      value={value.antiRaidJoinThreshold}
                      onChange={(event) =>
                        setValue((prev) => ({
                          ...prev,
                          antiRaidJoinThreshold: Number(event.target.value) || 1
                        }))
                      }
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>{t('modulePages.automod.antiRaidWindowSeconds')}</Label>
                    <Input
                      type="number"
                      min={1}
                      value={value.antiRaidWindowSeconds}
                      onChange={(event) =>
                        setValue((prev) => ({
                          ...prev,
                          antiRaidWindowSeconds: Number(event.target.value) || 1
                        }))
                      }
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>{t('modulePages.automod.antiRaidAction')}</Label>
                    <Select
                      value={value.antiRaidAction}
                      onValueChange={(antiRaidAction) =>
                        setValue((prev) => ({
                          ...prev,
                          antiRaidAction: antiRaidAction as AutomodConfigDashboard['antiRaidAction']
                        }))
                      }
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="LOCKDOWN">
                          {t('modulePages.automod.antiRaidActions.LOCKDOWN')}
                        </SelectItem>
                        <SelectItem value="VERIFY">
                          {t('modulePages.automod.antiRaidActions.VERIFY')}
                        </SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                <p className="text-sm text-muted-foreground">{t('modulePages.automod.antiRaidActionHint')}</p>
              </CardContent>
            </Card>
          </FieldAnchor>

          <FieldAnchor id="field-anti-nuke">
            <Card>
              <CardHeader>
                <CardTitle>{t('modulePages.automod.antiNukeTitle')}</CardTitle>
                <CardDescription>{t('modulePages.automod.antiNukeDescription')}</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-center justify-between rounded-md border border-border p-4">
                  <Label>{t('modulePages.automod.antiNukeEnabled')}</Label>
                  <Switch
                    checked={value.antiNukeEnabled}
                    onCheckedChange={(checked) =>
                      setValue((prev) => ({ ...prev, antiNukeEnabled: checked }))
                    }
                  />
                </div>
                <div className="grid gap-4 sm:grid-cols-3">
                  <div className="space-y-2">
                    <Label>{t('modulePages.automod.antiNukeBanThreshold')}</Label>
                    <Input
                      type="number"
                      min={1}
                      value={value.antiNukeBanThreshold}
                      onChange={(event) =>
                        setValue((prev) => ({
                          ...prev,
                          antiNukeBanThreshold: Number(event.target.value) || 1
                        }))
                      }
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>{t('modulePages.automod.antiNukeChannelThreshold')}</Label>
                    <Input
                      type="number"
                      min={1}
                      value={value.antiNukeChannelThreshold}
                      onChange={(event) =>
                        setValue((prev) => ({
                          ...prev,
                          antiNukeChannelThreshold: Number(event.target.value) || 1
                        }))
                      }
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>{t('modulePages.automod.antiNukeWindowSeconds')}</Label>
                    <Input
                      type="number"
                      min={1}
                      value={value.antiNukeWindowSeconds}
                      onChange={(event) =>
                        setValue((prev) => ({
                          ...prev,
                          antiNukeWindowSeconds: Number(event.target.value) || 1
                        }))
                      }
                    />
                  </div>
                </div>
                <FieldAnchor id="field-lockdown">
                  <div className="flex items-center justify-between rounded-md border border-border p-4">
                    <div className="space-y-0.5">
                      <Label>{t('modulePages.automod.lockdownActive')}</Label>
                      <p className="text-sm text-muted-foreground">
                        {t('modulePages.automod.lockdownActiveHint')}
                      </p>
                    </div>
                    <Switch
                      checked={value.lockdownActive}
                      onCheckedChange={(checked) =>
                        setValue((prev) => ({ ...prev, lockdownActive: checked }))
                      }
                    />
                  </div>
                </FieldAnchor>
              </CardContent>
            </Card>
          </FieldAnchor>
        </div>
      )}
    </SettingsForm>
  );
}
