import { useState } from 'react'
import type { AdminSettingRecord } from '@/lib/api/types'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import type { GroupConfig } from '../groups-config'
import { getSeoSubGroup } from '../groups-config'
import { SettingField } from './setting-field'

export function SettingsGroupPanel({
  group,
  settings,
  values,
  onChange,
}: {
  group: GroupConfig
  settings: AdminSettingRecord[]
  values: Record<string, string>
  onChange: (key: string, value: string) => void
}) {
  const sorted = [...settings].sort(
    (a, b) => (a.orderIndex ?? 0) - (b.orderIndex ?? 0)
  )

  if (group.subGroups && group.key === 'seo') {
    return (
      <SeoGroupPanel
        group={group}
        settings={sorted}
        values={values}
        onChange={onChange}
      />
    )
  }

  return (
    <div className='space-y-5'>
      {sorted.map((setting) => (
        <SettingField
          key={setting.id}
          setting={setting}
          value={values[setting.key] ?? ''}
          onChange={(v) => onChange(setting.key, v)}
        />
      ))}
      {sorted.length === 0 && (
        <p className='py-8 text-center text-sm text-muted-foreground'>
          Bu grupta henüz ayar bulunmuyor.
        </p>
      )}
    </div>
  )
}

function SeoGroupPanel({
  group,
  settings,
  values,
  onChange,
}: {
  group: GroupConfig
  settings: AdminSettingRecord[]
  values: Record<string, string>
  onChange: (key: string, value: string) => void
}) {
  const [activeSubTab, setActiveSubTab] = useState('basic')
  const subGroups = group.subGroups!

  const grouped: Record<string, AdminSettingRecord[]> = {}
  for (const sg of subGroups) {
    grouped[sg.key] = []
  }
  for (const setting of settings) {
    const sub = getSeoSubGroup(setting.key)
    if (!grouped[sub]) grouped[sub] = []
    grouped[sub].push(setting)
  }

  return (
    <Tabs value={activeSubTab} onValueChange={setActiveSubTab}>
      <TabsList className='mb-4'>
        {subGroups.map((sg) => (
          <TabsTrigger key={sg.key} value={sg.key} className='text-xs'>
            {sg.label}
          </TabsTrigger>
        ))}
      </TabsList>
      {subGroups.map((sg) => (
        <TabsContent key={sg.key} value={sg.key}>
          <div className='space-y-5'>
            {(grouped[sg.key] ?? []).map((setting) => (
              <SettingField
                key={setting.id}
                setting={setting}
                value={values[setting.key] ?? ''}
                onChange={(v) => onChange(setting.key, v)}
              />
            ))}
            {(grouped[sg.key] ?? []).length === 0 && (
              <p className='py-6 text-center text-sm text-muted-foreground'>
                Bu bölümde henüz ayar yok.
              </p>
            )}
          </div>
        </TabsContent>
      ))}
    </Tabs>
  )
}
