'use client';

import type { TicketConfigDashboard } 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import type { SettingsSaveResult } from '@/components/settings/settings-form';
import { SettingsForm } from '@/components/settings/settings-form';

async function saveTicketConfig(
  guildId: string,
  value: TicketConfigDashboard,
  errorMessages: {
    timeout: string;
    notPosted: string;
    noCategories: string;
    network: string;
  }
): Promise<SettingsSaveResult> {
  try {
    const response = await fetch(`/api/guilds/${guildId}/tickets`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(value)
    });
    if (!response.ok) {
      const body = (await response.json().catch(() => null)) as {
        error?: string;
        code?: string;
      } | null;
      if (body?.code === 'timeout') {
        return { ok: false, error: errorMessages.timeout };
      }
      if (body?.code === 'no_categories') {
        return { ok: false, error: errorMessages.noCategories };
      }
      if (body?.code === 'not_posted') {
        return { ok: false, error: errorMessages.notPosted };
      }
      return { ok: false, error: body?.error ?? `Request failed with status ${response.status}` };
    }
    return { ok: true };
  } catch {
    return { ok: false, error: errorMessages.network };
  }
}

interface TicketConfigFormProps {
  guildId: string;
  initialValue: TicketConfigDashboard;
}

export function TicketConfigForm({ guildId, initialValue }: TicketConfigFormProps) {
  const t = useTranslations();
  const inactivityId = useId();

  return (
    <SettingsForm<TicketConfigDashboard>
      initialValue={initialValue}
      onSave={(value) =>
        saveTicketConfig(guildId, value, {
          timeout: t('modulePages.tickets.errors.panelTimeout'),
          notPosted: t('modulePages.tickets.errors.panelNotPosted'),
          noCategories: t('modulePages.tickets.errors.noCategories'),
          network: t('common.networkError')
        })
      }
    >
      {({ value, setValue }) => (
        <Card>
          <CardHeader>
            <CardTitle>{t('modulePages.tickets.title')}</CardTitle>
            <CardDescription>{t('modulePages.tickets.description')}</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <FieldAnchor id="field-tickets-enabled">
            <div className="flex items-center justify-between rounded-md border border-border p-4">
              <Label>{t('modulePages.tickets.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-tickets-mode">
              <div className="space-y-2">
                <Label>{t('modulePages.tickets.mode')}</Label>
                <Select value={value.mode} onValueChange={(mode) => setValue((prev) => ({ ...prev, mode: mode as TicketConfigDashboard['mode'] }))}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="CHANNEL">{t('modulePages.tickets.modes.CHANNEL')}</SelectItem>
                    <SelectItem value="THREAD">{t('modulePages.tickets.modes.THREAD')}</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              </FieldAnchor>

              <FieldAnchor id="field-tickets-panel-channel">
              <div className="space-y-2">
                <Label>{t('modulePages.tickets.panelChannelId')}</Label>
                <DiscordChannelSelect
                  guildId={guildId}
                  value={value.panelChannelId}
                  onChange={(panelChannelId) => setValue((prev) => ({ ...prev, panelChannelId }))}
                />
                <p className="text-xs text-muted-foreground">{t('modulePages.tickets.panelChannelHint')}</p>
              </div>
              </FieldAnchor>

              <FieldAnchor id="field-tickets-category">
              <div className="space-y-2">
                <Label>{t('modulePages.tickets.categoryId')}</Label>
                <DiscordChannelSelect
                  guildId={guildId}
                  kinds={['category']}
                  value={value.categoryId}
                  onChange={(categoryId) => setValue((prev) => ({ ...prev, categoryId }))}
                />
              </div>
              </FieldAnchor>

              <FieldAnchor id="field-tickets-log">
              <div className="space-y-2">
                <Label>{t('modulePages.tickets.logChannelId')}</Label>
                <DiscordChannelSelect
                  guildId={guildId}
                  value={value.logChannelId}
                  onChange={(logChannelId) => setValue((prev) => ({ ...prev, logChannelId }))}
                />
              </div>
              </FieldAnchor>

              <FieldAnchor id="field-tickets-inactivity">
              <div className="space-y-2">
                <Label htmlFor={inactivityId}>{t('modulePages.tickets.inactivityHours')}</Label>
                <Input
                  id={inactivityId}
                  type="number"
                  min={1}
                  value={value.inactivityHours}
                  onChange={(event) =>
                    setValue((prev) => ({ ...prev, inactivityHours: Number(event.target.value) || 1 }))
                  }
                />
              </div>
              </FieldAnchor>
            </div>

            <FieldAnchor id="field-tickets-transcript">
            <div className="flex items-center justify-between rounded-md border border-border p-4">
              <div className="space-y-0.5">
                <Label>{t('modulePages.tickets.transcriptDm')}</Label>
                <p className="text-sm text-muted-foreground">{t('modulePages.tickets.transcriptDmHint')}</p>
              </div>
              <Switch
                checked={value.transcriptDm}
                onCheckedChange={(transcriptDm) => setValue((prev) => ({ ...prev, transcriptDm }))}
              />
            </div>
            </FieldAnchor>

            <FieldAnchor id="field-tickets-rating">
            <div className="flex items-center justify-between rounded-md border border-border p-4">
              <Label>{t('modulePages.tickets.ratingEnabled')}</Label>
              <Switch
                checked={value.ratingEnabled}
                onCheckedChange={(ratingEnabled) => setValue((prev) => ({ ...prev, ratingEnabled }))}
              />
            </div>
            </FieldAnchor>
          </CardContent>
        </Card>
      )}
    </SettingsForm>
  );
}
