'use client';

import { DASHBOARD_MODULES, type DashboardModuleGroup, type DashboardModuleId, type ModuleStatus } from '@nexumi/shared';
import { ArrowUpRight } from 'lucide-react';
import Link from 'next/link';
import { useTranslations } from '@/components/locale-provider';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Switch } from '@/components/ui/switch';
import type { SettingsSaveResult } from './settings-form';
import { SettingsForm } from './settings-form';

type ModuleToggleValue = Record<DashboardModuleId, boolean>;

const MODULE_GROUP_ORDER: DashboardModuleGroup[] = [
  'moderation',
  'engagement',
  'community',
  'utility',
  'integrations'
];

function toValue(statuses: ModuleStatus[]): ModuleToggleValue {
  return statuses.reduce<ModuleToggleValue>((acc, status) => {
    acc[status.id] = status.enabled;
    return acc;
  }, {} as ModuleToggleValue);
}

async function saveModules(guildId: string, value: ModuleToggleValue): Promise<SettingsSaveResult> {
  try {
    const response = await fetch(`/api/guilds/${guildId}/modules`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ modules: 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 ModuleTogglesFormProps {
  guildId: string;
  initialStatuses: ModuleStatus[];
}

export function ModuleTogglesForm({ guildId, initialStatuses }: ModuleTogglesFormProps) {
  const t = useTranslations();

  return (
    <SettingsForm<ModuleToggleValue>
      initialValue={toValue(initialStatuses)}
      onSave={(value) => saveModules(guildId, value)}
    >
      {({ value, setValue }) => (
        <div className="space-y-6">
          {MODULE_GROUP_ORDER.map((group) => {
            const modules = DASHBOARD_MODULES.filter((module) => module.group === group);
            return (
              <Card key={group}>
                <CardHeader>
                  <CardTitle>{t(`moduleGroups.${group}`)}</CardTitle>
                </CardHeader>
                <CardContent className="divide-y divide-border">
                  {modules.map((module) => (
                    <div key={module.id} className="flex items-center justify-between gap-4 py-3 first:pt-0 last:pb-0">
                      <div className="min-w-0 space-y-0.5">
                        <div className="flex items-center gap-2">
                          <p className="font-medium">{t(`modules.${module.id}.label`)}</p>
                          <Link
                            href={`/dashboard/${guildId}/${module.href}`}
                            className="inline-flex items-center gap-0.5 text-xs text-muted-foreground hover:text-foreground"
                          >
                            {t('modulesPage.configure')}
                            <ArrowUpRight className="size-3" />
                          </Link>
                        </div>
                        <p className="truncate text-sm text-muted-foreground">
                          {t(`modules.${module.id}.description`)}
                        </p>
                      </div>
                      <Switch
                        checked={value[module.id] ?? false}
                        onCheckedChange={(checked) =>
                          setValue((prev) => ({ ...prev, [module.id]: checked }))
                        }
                      />
                    </div>
                  ))}
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}
    </SettingsForm>
  );
}
