'use client';

import type { StatsConfigDashboard } from '@nexumi/shared';
import { useId } from 'react';
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 { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { PlaceholderHelp } from '@/components/ui/placeholder-help';
import { Switch } from '@/components/ui/switch';
import type { SettingsSaveResult } from '@/components/settings/settings-form';
import { SettingsForm } from '@/components/settings/settings-form';

async function saveStats(guildId: string, value: StatsConfigDashboard): Promise<SettingsSaveResult> {
  try {
    const response = await fetch(`/api/guilds/${guildId}/stats`, {
      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 StatsFormProps {
  guildId: string;
  initialValue: StatsConfigDashboard;
}

export function StatsForm({ guildId, initialValue }: StatsFormProps) {
  const t = useTranslations();
  const membersTemplateId = useId();
  const onlineTemplateId = useId();
  const boostsTemplateId = useId();

  return (
    <SettingsForm<StatsConfigDashboard> initialValue={initialValue} onSave={(value) => saveStats(guildId, value)}>
      {({ value, setValue }) => (
        <Card>
          <CardHeader>
            <CardTitle>{t('modulePages.stats.title')}</CardTitle>
            <CardDescription>{t('modulePages.stats.description')}</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <FieldAnchor id="field-stats-enabled">
            <div className="flex items-center justify-between rounded-md border border-border p-4">
              <Label>{t('modulePages.stats.enabledLabel')}</Label>
              <Switch checked={value.enabled} onCheckedChange={(enabled) => setValue((prev) => ({ ...prev, enabled }))} />
            </div>
            </FieldAnchor>
            <div className="grid gap-4 sm:grid-cols-2">
              <FieldAnchor id="field-stats-members">
              <div className="space-y-2">
                <Label>{t('modulePages.stats.membersChannelId')}</Label>
                <DiscordChannelSelect
                  guildId={guildId}
                  kinds={['voice']}
                  value={value.membersChannelId}
                  onChange={(membersChannelId) => setValue((prev) => ({ ...prev, membersChannelId }))}
                />
              </div>
              </FieldAnchor>
              <div className="space-y-2">
                <Label htmlFor={membersTemplateId}>{t('modulePages.stats.membersTemplate')}</Label>
                <Input id={membersTemplateId} value={value.membersTemplate} onChange={(event) => setValue((prev) => ({ ...prev, membersTemplate: event.target.value }))} />
              </div>
              <FieldAnchor id="field-stats-online">
              <div className="space-y-2">
                <Label>{t('modulePages.stats.onlineChannelId')}</Label>
                <DiscordChannelSelect
                  guildId={guildId}
                  kinds={['voice']}
                  value={value.onlineChannelId}
                  onChange={(onlineChannelId) => setValue((prev) => ({ ...prev, onlineChannelId }))}
                />
              </div>
              </FieldAnchor>
              <div className="space-y-2">
                <Label htmlFor={onlineTemplateId}>{t('modulePages.stats.onlineTemplate')}</Label>
                <Input id={onlineTemplateId} value={value.onlineTemplate} onChange={(event) => setValue((prev) => ({ ...prev, onlineTemplate: event.target.value }))} />
              </div>
              <FieldAnchor id="field-stats-boosts">
              <div className="space-y-2">
                <Label>{t('modulePages.stats.boostsChannelId')}</Label>
                <DiscordChannelSelect
                  guildId={guildId}
                  kinds={['voice']}
                  value={value.boostsChannelId}
                  onChange={(boostsChannelId) => setValue((prev) => ({ ...prev, boostsChannelId }))}
                />
              </div>
              </FieldAnchor>
              <div className="space-y-2">
                <Label htmlFor={boostsTemplateId}>{t('modulePages.stats.boostsTemplate')}</Label>
                <Input id={boostsTemplateId} value={value.boostsTemplate} onChange={(event) => setValue((prev) => ({ ...prev, boostsTemplate: event.target.value }))} />
              </div>
            </div>
            <PlaceholderHelp preset="stats" />
          </CardContent>
        </Card>
      )}
    </SettingsForm>
  );
}
