import { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { FormPage } from '@/components/templates'
import { Card, Field, ImageUpload, SegmentedControl, useToast } from '@/components/ui'
import { ThemeColourPicker } from '@/features/superadmin/ThemeColourPicker'
import {
  useBrandingSettings,
  useLocalForm,
  useUpdateBrandingSettings,
  type BrandingSettings,
} from '../hooks'
import { serverMessage } from '@/lib/api'

const empty: BrandingSettings = {
  logo: null, logo_url: null, logo_dark: null, logo_dark_url: null,
  favicon: null, favicon_url: null, accent_hex: null, default_theme: 'system',
}

/**
 * Theme (T3, tab-less) — logo, favicon, accent colour and default light/dark
 * appearance, all one screen. Used to be two: a `identity` section here held
 * only the logo, so a shop had to visit a separate "Logo & identity" page to
 * set the one mark that belongs beside its colour. `/settings/branding`
 * redirects here now (routes.tsx), the same merge shape as
 * `/settings/checkout` + `/settings/till` → `/settings/pos`.
 */
export function BrandingThemePage() {
  const { t } = useTranslation()
  const toast = useToast()
  const { data, isLoading } = useBrandingSettings()
  const save = useUpdateBrandingSettings()
  const form = useLocalForm<BrandingSettings>(empty)

  useEffect(() => {
    if (data) form.reset(data)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data])

  const v = form.value

  const onSave = () => {
    save.mutate(v, {
      onSuccess: () => {
        toast.success(t('Branding saved'), t('Your logo and theme were updated.'))
        form.markSaved()
      },
      onError: (e) => toast.danger(t('Could not save'), serverMessage(e, t('Please try again.'))),
    })
  }

  return (
    <FormPage
      writePermission='Manage Settings'
      title={t('Theme')}
      microcopy={t('The logo and favicon that mark the app as your shop, in the header and browser tab.')}
      dirty={form.dirty}
      saving={save.isPending}
      onSave={onSave}
      onDiscard={() => data && form.reset(data)}
    >
      {isLoading ? null : (
        <div className="flex flex-col gap-5">
          <Card title={t('Accent colour')} subtitle={t('Drives buttons, links and highlights')}>
            <ThemeColourPicker value={v.accent_hex ?? ''} onChange={(hex) => form.set({ accent_hex: hex })} />
          </Card>

          <Card title={t('Logo & favicon')} subtitle={t('The logo and favicon that mark the app as your shop, in the header and browser tab.')}>
            <div className="grid gap-5 sm:grid-cols-2">
              <Field label={t('Logo')} help={t('A transparent PNG works best. Also used on the receipt when logo printing is on.')}>
                <ImageUpload
                  value={v.logo_url}
                  folder="logo"
                  onUploaded={(f) => form.set({ logo: f.filename, logo_url: f.url })}
                  onClear={() => form.set({ logo: null, logo_url: null })}
                />
              </Field>
              {/*
                Optional. Without one, dark mode just keeps showing the logo
                above — which is fine for most marks (that's what "a
                transparent PNG works best" is already for) and only falls
                short for a logo that reads fine on a light sidebar and
                disappears once html.dark flips the background behind it.
              */}
              <Field label={t('Logo (dark mode)')} help={t('Only needed if your regular logo is hard to see once your staff switch to dark mode. Leave empty to keep using the logo above.')}>
                <ImageUpload
                  value={v.logo_dark_url}
                  folder="logo"
                  onUploaded={(f) => form.set({ logo_dark: f.filename, logo_dark_url: f.url })}
                  onClear={() => form.set({ logo_dark: null, logo_dark_url: null })}
                />
              </Field>
              <Field label={t('Favicon')} help={t('The browser tab icon. Used at every size, so a simple square mark works best.')}>
                <ImageUpload
                  value={v.favicon_url}
                  folder="favicon"
                  accept="image/png,image/x-icon,image/svg+xml"
                  onUploaded={(f) => form.set({ favicon: f.filename, favicon_url: f.url })}
                  onClear={() => form.set({ favicon: null, favicon_url: null })}
                />
              </Field>
            </div>
          </Card>

          <Card title={t('Default appearance')} subtitle={t('What your staff get before they choose for themselves')}>
            <Field help={t('Anyone who has picked light or dark keeps their own choice.')}>
              <SegmentedControl<'light' | 'dark' | 'system'>
                value={v.default_theme}
                onChange={(x) => form.set({ default_theme: x })}
                options={[{ value: 'light', label: t('Light') }, { value: 'dark', label: t('Dark') }, { value: 'system', label: t('System') }]}
                aria-label={t('Default appearance')}
              />
            </Field>
          </Card>
        </div>
      )}
    </FormPage>
  )
}

export default BrandingThemePage
