'use client';

import type { SuggestionConfigDashboard } 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 { DiscordChannelSelect } from '@/components/ui/discord-channel-select';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import type { SettingsSaveResult } from '@/components/settings/settings-form';
import { SettingsForm } from '@/components/settings/settings-form';

async function saveSuggestionsConfig(
  guildId: string,
  value: SuggestionConfigDashboard
): Promise<SettingsSaveResult> {
  try {
    const response = await fetch(`/api/guilds/${guildId}/suggestions`, {
      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' };
  }
}

interface SuggestionsConfigFormProps {
  guildId: string;
  initialValue: SuggestionConfigDashboard;
}

export function SuggestionsConfigForm({ guildId, initialValue }: SuggestionsConfigFormProps) {
  const t = useTranslations();

  return (
    <SettingsForm<SuggestionConfigDashboard>
      initialValue={initialValue}
      onSave={(value) => saveSuggestionsConfig(guildId, value)}
    >
      {({ value, setValue }) => (
        <Card>
          <CardHeader>
            <CardTitle>{t('modulePages.suggestions.configTitle')}</CardTitle>
            <CardDescription>{t('modulePages.suggestions.configDescription')}</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <FieldAnchor id="field-suggestions-enabled">
            <div className="flex items-center justify-between rounded-md border border-border p-4">
              <Label>{t('modulePages.suggestions.enabledLabel')}</Label>
              <Switch checked={value.enabled} onCheckedChange={(enabled) => setValue((prev) => ({ ...prev, enabled }))} />
            </div>
            </FieldAnchor>
            <div className="grid gap-4 sm:grid-cols-3">
              <FieldAnchor id="field-suggestions-open">
              <div className="space-y-2">
                <Label>{t('modulePages.suggestions.openChannelId')}</Label>
                <DiscordChannelSelect
                  guildId={guildId}
                  value={value.openChannelId}
                  onChange={(openChannelId) => setValue((prev) => ({ ...prev, openChannelId }))}
                />
              </div>
              </FieldAnchor>
              <FieldAnchor id="field-suggestions-approved">
              <div className="space-y-2">
                <Label>{t('modulePages.suggestions.approvedChannelId')}</Label>
                <DiscordChannelSelect
                  guildId={guildId}
                  value={value.approvedChannelId}
                  onChange={(approvedChannelId) => setValue((prev) => ({ ...prev, approvedChannelId }))}
                  placeholder={t('common.optional')}
                />
              </div>
              </FieldAnchor>
              <FieldAnchor id="field-suggestions-denied">
              <div className="space-y-2">
                <Label>{t('modulePages.suggestions.deniedChannelId')}</Label>
                <DiscordChannelSelect
                  guildId={guildId}
                  value={value.deniedChannelId}
                  onChange={(deniedChannelId) => setValue((prev) => ({ ...prev, deniedChannelId }))}
                  placeholder={t('common.optional')}
                />
              </div>
              </FieldAnchor>
            </div>
            <FieldAnchor id="field-suggestions-thread">
            <div className="flex items-center justify-between rounded-md border border-border p-4">
              <div className="space-y-0.5">
                <Label>{t('modulePages.suggestions.createThread')}</Label>
                <p className="text-sm text-muted-foreground">{t('modulePages.suggestions.createThreadHint')}</p>
              </div>
              <Switch checked={value.createThread} onCheckedChange={(createThread) => setValue((prev) => ({ ...prev, createThread }))} />
            </div>
            </FieldAnchor>
          </CardContent>
        </Card>
      )}
    </SettingsForm>
  );
}
