'use client';

import type { TempVoiceConfigDashboard } 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 saveTempVoice(guildId: string, value: TempVoiceConfigDashboard): Promise<SettingsSaveResult> {
  try {
    const response = await fetch(`/api/guilds/${guildId}/tempvoice`, {
      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 TempVoiceFormProps {
  guildId: string;
  initialValue: TempVoiceConfigDashboard;
}

export function TempVoiceForm({ guildId, initialValue }: TempVoiceFormProps) {
  const t = useTranslations();
  const nameId = useId();
  const limitId = useId();

  return (
    <SettingsForm<TempVoiceConfigDashboard> initialValue={initialValue} onSave={(value) => saveTempVoice(guildId, value)}>
      {({ value, setValue }) => (
        <Card>
          <CardHeader>
            <CardTitle>{t('modulePages.tempvoice.title')}</CardTitle>
            <CardDescription>{t('modulePages.tempvoice.description')}</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <FieldAnchor id="field-tempvoice-enabled">
            <div className="flex items-center justify-between rounded-md border border-border p-4">
              <Label>{t('modulePages.tempvoice.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-tempvoice-hub">
              <div className="space-y-2">
                <Label>{t('modulePages.tempvoice.hubChannelId')}</Label>
                <DiscordChannelSelect
                  guildId={guildId}
                  kinds={['voice']}
                  value={value.hubChannelId}
                  onChange={(hubChannelId) => setValue((prev) => ({ ...prev, hubChannelId }))}
                />
              </div>
              </FieldAnchor>
              <FieldAnchor id="field-tempvoice-category">
              <div className="space-y-2">
                <Label>{t('modulePages.tempvoice.categoryId')}</Label>
                <DiscordChannelSelect
                  guildId={guildId}
                  kinds={['category']}
                  value={value.categoryId}
                  onChange={(categoryId) => setValue((prev) => ({ ...prev, categoryId }))}
                />
              </div>
              </FieldAnchor>
              <FieldAnchor id="field-tempvoice-name">
              <div className="space-y-2">
                <Label htmlFor={nameId}>{t('modulePages.tempvoice.defaultName')}</Label>
                <Input id={nameId} value={value.defaultName} onChange={(event) => setValue((prev) => ({ ...prev, defaultName: event.target.value }))} placeholder="{user}'s Channel" />
                <PlaceholderHelp preset="tempvoice" />
              </div>
              </FieldAnchor>
              <FieldAnchor id="field-tempvoice-limit">
              <div className="space-y-2">
                <Label htmlFor={limitId}>{t('modulePages.tempvoice.defaultLimit')}</Label>
                <Input id={limitId} type="number" min={0} max={99} value={value.defaultLimit} onChange={(event) => setValue((prev) => ({ ...prev, defaultLimit: Number(event.target.value) || 0 }))} />
              </div>
              </FieldAnchor>
            </div>
            <p className="text-xs text-muted-foreground">{t('modulePages.tempvoice.defaultLimitHint')}</p>
          </CardContent>
        </Card>
      )}
    </SettingsForm>
  );
}
