'use client';

import type { EconomyConfigDashboard } from '@nexumi/shared';
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 { Switch } from '@/components/ui/switch';
import type { SettingsSaveResult } from '@/components/settings/settings-form';
import { SettingsForm } from '@/components/settings/settings-form';

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

export function EconomyForm({ guildId, initialValue }: EconomyFormProps) {
  const t = useTranslations();

  return (
    <SettingsForm<EconomyConfigDashboard> initialValue={initialValue} onSave={(value) => saveEconomy(guildId, value)}>
      {({ value, setValue }) => (
        <div className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>{t('modulePages.economy.title')}</CardTitle>
              <CardDescription>{t('modulePages.economy.description')}</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center justify-between rounded-md border border-border p-4">
                <Label>{t('modulePages.economy.enabledLabel')}</Label>
                <Switch
                  checked={value.enabled}
                  onCheckedChange={(checked) => setValue((prev) => ({ ...prev, enabled: checked }))}
                />
              </div>
              <div className="grid gap-4 sm:grid-cols-2">
                <div className="space-y-2">
                  <Label>{t('modulePages.economy.currencyName')}</Label>
                  <Input
                    value={value.currencyName}
                    onChange={(event) => setValue((prev) => ({ ...prev, currencyName: event.target.value }))}
                  />
                </div>
                <div className="space-y-2">
                  <Label>{t('modulePages.economy.currencySymbol')}</Label>
                  <Input
                    value={value.currencySymbol}
                    onChange={(event) => setValue((prev) => ({ ...prev, currencySymbol: event.target.value }))}
                  />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>{t('modulePages.economy.amountsTitle')}</CardTitle>
            </CardHeader>
            <CardContent className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label>{t('modulePages.economy.dailyAmount')}</Label>
                <Input
                  type="number"
                  min={0}
                  value={value.dailyAmount}
                  onChange={(event) => setValue((prev) => ({ ...prev, dailyAmount: Number(event.target.value) || 0 }))}
                />
              </div>
              <div className="space-y-2">
                <Label>{t('modulePages.economy.weeklyAmount')}</Label>
                <Input
                  type="number"
                  min={0}
                  value={value.weeklyAmount}
                  onChange={(event) => setValue((prev) => ({ ...prev, weeklyAmount: Number(event.target.value) || 0 }))}
                />
              </div>
              <div className="space-y-2">
                <Label>{t('modulePages.economy.workMin')}</Label>
                <Input
                  type="number"
                  min={0}
                  value={value.workMin}
                  onChange={(event) => setValue((prev) => ({ ...prev, workMin: Number(event.target.value) || 0 }))}
                />
              </div>
              <div className="space-y-2">
                <Label>{t('modulePages.economy.workMax')}</Label>
                <Input
                  type="number"
                  min={0}
                  value={value.workMax}
                  onChange={(event) => setValue((prev) => ({ ...prev, workMax: Number(event.target.value) || 0 }))}
                />
              </div>
              <div className="space-y-2">
                <Label>{t('modulePages.economy.workCooldownSeconds')}</Label>
                <Input
                  type="number"
                  min={1}
                  value={value.workCooldownSeconds}
                  onChange={(event) =>
                    setValue((prev) => ({ ...prev, workCooldownSeconds: Number(event.target.value) || 1 }))
                  }
                />
              </div>
              <div className="space-y-2">
                <Label>{t('modulePages.economy.startingBalance')}</Label>
                <Input
                  type="number"
                  min={0}
                  value={value.startingBalance}
                  onChange={(event) =>
                    setValue((prev) => ({ ...prev, startingBalance: Number(event.target.value) || 0 }))
                  }
                />
              </div>
            </CardContent>
          </Card>
        </div>
      )}
    </SettingsForm>
  );
}
