'use client';

import type { GuildGeneralSettings } 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 { 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 './settings-form';
import { SettingsForm } from './settings-form';

interface GeneralSettingsFormProps {
  guildId: string;
  initialSettings: GuildGeneralSettings;
}

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

export function GeneralSettingsForm({ guildId, initialSettings }: GeneralSettingsFormProps) {
  const t = useTranslations();

  return (
    <SettingsForm<GuildGeneralSettings>
      initialValue={initialSettings}
      onSave={(value) => saveGeneralSettings(guildId, value)}
    >
      {({ value, setValue }) => (
        <Card>
          <CardHeader>
            <CardTitle>{t('settings.general.title')}</CardTitle>
            <CardDescription>{t('settings.general.description')}</CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <FieldAnchor id="field-locale">
              <div className="space-y-2">
                <Label htmlFor="general-locale">{t('settings.general.localeLabel')}</Label>
                <Select
                  value={value.locale}
                  onValueChange={(locale) => setValue((prev) => ({ ...prev, locale: locale as 'de' | 'en' }))}
                >
                  <SelectTrigger id="general-locale" className="w-56">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="de">Deutsch</SelectItem>
                    <SelectItem value="en">English</SelectItem>
                  </SelectContent>
                </Select>
                <p className="text-sm text-muted-foreground">{t('settings.general.localeHint')}</p>
              </div>
            </FieldAnchor>

            <FieldAnchor id="field-timezone">
              <div className="space-y-2">
                <Label htmlFor="general-timezone">{t('settings.general.timezoneLabel')}</Label>
                <Input
                  id="general-timezone"
                  className="w-72"
                  value={value.timezone}
                  onChange={(event) => setValue((prev) => ({ ...prev, timezone: event.target.value }))}
                  placeholder="Europe/Berlin"
                />
                <p className="text-sm text-muted-foreground">{t('settings.general.timezoneHint')}</p>
              </div>
            </FieldAnchor>

            <FieldAnchor id="field-moderation-toggle">
              <div className="flex items-center justify-between rounded-md border border-border p-4">
                <div className="space-y-0.5">
                  <Label htmlFor="general-moderation">{t('settings.general.moderationLabel')}</Label>
                  <p className="text-sm text-muted-foreground">{t('settings.general.moderationHint')}</p>
                </div>
                <Switch
                  id="general-moderation"
                  checked={value.moderationEnabled}
                  onCheckedChange={(checked) => setValue((prev) => ({ ...prev, moderationEnabled: checked }))}
                />
              </div>
            </FieldAnchor>

            <FieldAnchor id="field-snipe">
              <div className="flex items-center justify-between rounded-md border border-border p-4">
                <div className="space-y-0.5">
                  <Label htmlFor="general-snipe">{t('settings.general.snipeLabel')}</Label>
                  <p className="text-sm text-muted-foreground">{t('settings.general.snipeHint')}</p>
                </div>
                <Switch
                  id="general-snipe"
                  checked={value.snipeEnabled}
                  onCheckedChange={(checked) => setValue((prev) => ({ ...prev, snipeEnabled: checked }))}
                />
              </div>
            </FieldAnchor>
          </CardContent>
        </Card>
      )}
    </SettingsForm>
  );
}
