'use client'

import { useEffect, useState } from 'react'
import { apiFetch } from '@/lib/api'

interface BrandSettings {
  displayName: string
  tagline: string | null
  primaryColor: string
  accentColor?: string | null
  publicEmail: string | null
  publicPhone: string | null
  publicAddress?: string | null
  publicCity: string | null
  publicCountry?: string | null
  subdomain: string
  logoUrl?: string | null
  heroImageUrl?: string | null
  websiteUrl?: string | null
  whatsappNumber?: string | null
  paypalEmail: string | null
  amanpayMerchantId: string | null
  amanpaySecretKey?: string | null
  paypalMerchantId?: string | null
  customDomain?: string | null
  customDomainVerified?: boolean
  defaultCurrency?: string
  isListedOnMarketplace: boolean
}

interface ContractSettings {
  fuelPolicyType: string
  fuelPolicyNote: string | null
  additionalDriverCharge: 'FREE' | 'PER_DAY' | 'FLAT'
  additionalDriverDailyRate: number
  additionalDriverFlatRate: number
  damagePolicy: string
}

interface InsurancePolicy {
  id: string
  name: string
  type: string
  chargeType: string
  chargeValue: number
  isRequired: boolean
  isActive: boolean
}

interface PricingRule {
  id: string
  name: string
  type: string
  condition: string
  conditionValue: number
  adjustmentType: string
  adjustmentValue: number
  isActive: boolean
}

interface AccountingSettings {
  reportingPeriod: string
  accountantEmail: string | null
  accountantName: string | null
  autoSendReport: boolean
  reportFormat: string
}

const emptyInsurance = { name: '', type: 'BASIC', chargeType: 'PER_DAY', chargeValue: 0, isRequired: false, isActive: true }
const emptyRule = { name: '', type: 'SURCHARGE', condition: 'AGE_LESS_THAN', conditionValue: 25, adjustmentType: 'PERCENTAGE', adjustmentValue: 0, isActive: true }

export default function SettingsPage() {
  const [brand, setBrand] = useState<BrandSettings | null>(null)
  const [contractSettings, setContractSettings] = useState<ContractSettings | null>(null)
  const [insurancePolicies, setInsurancePolicies] = useState<InsurancePolicy[]>([])
  const [pricingRules, setPricingRules] = useState<PricingRule[]>([])
  const [accountingSettings, setAccountingSettings] = useState<AccountingSettings | null>(null)
  const [newInsurance, setNewInsurance] = useState(emptyInsurance)
  const [newRule, setNewRule] = useState(emptyRule)
  const [customDomain, setCustomDomain] = useState('')
  const [uploadingAsset, setUploadingAsset] = useState<'logo' | 'hero' | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [saving, setSaving] = useState(false)

  async function load() {
    try {
      const [brandData, contractData, insuranceData, ruleData, accountingData] = await Promise.all([
        apiFetch<BrandSettings | null>('/companies/me/brand'),
        apiFetch<ContractSettings | null>('/companies/me/contract-settings'),
        apiFetch<InsurancePolicy[]>('/companies/me/insurance-policies'),
        apiFetch<PricingRule[]>('/companies/me/pricing-rules'),
        apiFetch<AccountingSettings | null>('/companies/me/accounting-settings'),
      ])
      setBrand(brandData)
      setCustomDomain(brandData?.customDomain ?? '')
      setContractSettings(contractData ?? {
        fuelPolicyType: 'FULL_TO_FULL',
        fuelPolicyNote: '',
        additionalDriverCharge: 'FREE',
        additionalDriverDailyRate: 0,
        additionalDriverFlatRate: 0,
        damagePolicy: '',
      })
      setInsurancePolicies(insuranceData)
      setPricingRules(ruleData)
      setAccountingSettings(accountingData ?? {
        reportingPeriod: 'MONTHLY',
        accountantEmail: '',
        accountantName: '',
        autoSendReport: false,
        reportFormat: 'CSV',
      })
      setError(null)
    } catch (err: any) {
      setError(err.message ?? 'Failed to load settings')
    }
  }

  async function saveBrandSettings() {
    if (!brand) return
    setSaving(true)
    setError(null)
    try {
      const updated = await apiFetch<BrandSettings>('/companies/me/brand', {
        method: 'PATCH',
        body: JSON.stringify({
          displayName: brand.displayName,
          tagline: brand.tagline || undefined,
          primaryColor: brand.primaryColor,
          accentColor: brand.accentColor || undefined,
          publicEmail: brand.publicEmail || undefined,
          publicPhone: brand.publicPhone || undefined,
          publicAddress: brand.publicAddress || undefined,
          publicCity: brand.publicCity || undefined,
          publicCountry: brand.publicCountry || undefined,
          websiteUrl: brand.websiteUrl || undefined,
          whatsappNumber: brand.whatsappNumber || undefined,
          paypalEmail: brand.paypalEmail || undefined,
          amanpayMerchantId: brand.amanpayMerchantId || undefined,
          amanpaySecretKey: brand.amanpaySecretKey || undefined,
          paypalMerchantId: brand.paypalMerchantId || undefined,
          defaultCurrency: brand.defaultCurrency || undefined,
          isListedOnMarketplace: brand.isListedOnMarketplace,
        }),
      })
      setBrand(updated)
    } catch (err: any) {
      setError(err.message ?? 'Failed to save brand settings')
    } finally {
      setSaving(false)
    }
  }

  async function uploadBrandAsset(kind: 'logo' | 'hero', file: File | null) {
    if (!file) return
    setUploadingAsset(kind)
    setError(null)
    try {
      const formData = new FormData()
      formData.append('file', file)
      const updated = await apiFetch<BrandSettings>(`/companies/me/brand/${kind}`, {
        method: 'POST',
        body: formData,
      })
      setBrand(updated)
    } catch (err: any) {
      setError(err.message ?? `Failed to upload ${kind}`)
    } finally {
      setUploadingAsset(null)
    }
  }

  async function saveCustomDomain() {
    setSaving(true)
    setError(null)
    try {
      await apiFetch('/companies/me/brand/custom-domain', {
        method: 'POST',
        body: JSON.stringify({ customDomain }),
      })
      await load()
    } catch (err: any) {
      setError(err.message ?? 'Failed to save custom domain')
    } finally {
      setSaving(false)
    }
  }

  async function removeCustomDomain() {
    setSaving(true)
    setError(null)
    try {
      await apiFetch('/companies/me/brand/custom-domain', {
        method: 'DELETE',
      })
      setCustomDomain('')
      await load()
    } catch (err: any) {
      setError(err.message ?? 'Failed to remove custom domain')
    } finally {
      setSaving(false)
    }
  }

  useEffect(() => {
    load()
  }, [])

  async function saveContractSettings() {
    if (!contractSettings) return
    setSaving(true)
    setError(null)
    try {
      await apiFetch('/companies/me/contract-settings', {
        method: 'PATCH',
        body: JSON.stringify(contractSettings),
      })
    } catch (err: any) {
      setError(err.message ?? 'Failed to save contract settings')
    } finally {
      setSaving(false)
    }
  }

  async function saveAccountingSettings() {
    if (!accountingSettings) return
    setSaving(true)
    setError(null)
    try {
      await apiFetch('/companies/me/accounting-settings', {
        method: 'PATCH',
        body: JSON.stringify(accountingSettings),
      })
    } catch (err: any) {
      setError(err.message ?? 'Failed to save accounting settings')
    } finally {
      setSaving(false)
    }
  }

  async function createInsurance() {
    setSaving(true)
    setError(null)
    try {
      await apiFetch('/companies/me/insurance-policies', {
        method: 'POST',
        body: JSON.stringify(newInsurance),
      })
      setNewInsurance(emptyInsurance)
      await load()
    } catch (err: any) {
      setError(err.message ?? 'Failed to create insurance policy')
    } finally {
      setSaving(false)
    }
  }

  async function toggleInsurance(policy: InsurancePolicy) {
    try {
      await apiFetch(`/companies/me/insurance-policies/${policy.id}`, {
        method: 'PATCH',
        body: JSON.stringify({ isActive: !policy.isActive }),
      })
      await load()
    } catch (err: any) {
      setError(err.message ?? 'Failed to update insurance policy')
    }
  }

  async function createRule() {
    setSaving(true)
    setError(null)
    try {
      await apiFetch('/companies/me/pricing-rules', {
        method: 'POST',
        body: JSON.stringify(newRule),
      })
      setNewRule(emptyRule)
      await load()
    } catch (err: any) {
      setError(err.message ?? 'Failed to create pricing rule')
    } finally {
      setSaving(false)
    }
  }

  async function toggleRule(rule: PricingRule) {
    try {
      await apiFetch(`/companies/me/pricing-rules/${rule.id}`, {
        method: 'PATCH',
        body: JSON.stringify({ isActive: !rule.isActive }),
      })
      await load()
    } catch (err: any) {
      setError(err.message ?? 'Failed to update pricing rule')
    }
  }

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-xl font-semibold text-slate-900">Advanced settings</h2>
        <p className="mt-1 text-sm text-slate-500">Manage insurance, additional-driver rules, pricing adjustments, and reporting defaults.</p>
      </div>

      {error && <div className="card p-6 text-sm text-red-600">{error}</div>}

      {brand && (
        <div className="grid gap-6">
          <div className="card p-6">
            <div className="flex items-center justify-between gap-4">
              <div>
                <h3 className="text-base font-semibold text-slate-900">Brand and public profile</h3>
                <p className="mt-1 text-sm text-slate-500">Control how your company appears on the marketplace and public booking site.</p>
              </div>
              <button onClick={saveBrandSettings} disabled={saving} className="btn-primary">
                {saving ? 'Saving…' : 'Save brand'}
              </button>
            </div>
            <div className="mt-5 grid gap-4 lg:grid-cols-2">
              <div>
                <label className="mb-1.5 block text-sm font-medium text-slate-700">Display name</label>
                <input className="input-field" value={brand.displayName} onChange={(event) => setBrand((current) => current ? { ...current, displayName: event.target.value } : current)} />
              </div>
              <div>
                <label className="mb-1.5 block text-sm font-medium text-slate-700">Tagline</label>
                <input className="input-field" value={brand.tagline ?? ''} onChange={(event) => setBrand((current) => current ? { ...current, tagline: event.target.value } : current)} />
              </div>
              <div>
                <label className="mb-1.5 block text-sm font-medium text-slate-700">Public email</label>
                <input className="input-field" type="email" value={brand.publicEmail ?? ''} onChange={(event) => setBrand((current) => current ? { ...current, publicEmail: event.target.value } : current)} />
              </div>
              <div>
                <label className="mb-1.5 block text-sm font-medium text-slate-700">Public phone</label>
                <input className="input-field" value={brand.publicPhone ?? ''} onChange={(event) => setBrand((current) => current ? { ...current, publicPhone: event.target.value } : current)} />
              </div>
              <div>
                <label className="mb-1.5 block text-sm font-medium text-slate-700">City</label>
                <input className="input-field" value={brand.publicCity ?? ''} onChange={(event) => setBrand((current) => current ? { ...current, publicCity: event.target.value } : current)} />
              </div>
              <div>
                <label className="mb-1.5 block text-sm font-medium text-slate-700">Country</label>
                <input className="input-field" value={brand.publicCountry ?? ''} onChange={(event) => setBrand((current) => current ? { ...current, publicCountry: event.target.value } : current)} />
              </div>
              <div>
                <label className="mb-1.5 block text-sm font-medium text-slate-700">Website URL</label>
                <input className="input-field" value={brand.websiteUrl ?? ''} onChange={(event) => setBrand((current) => current ? { ...current, websiteUrl: event.target.value } : current)} />
              </div>
              <div>
                <label className="mb-1.5 block text-sm font-medium text-slate-700">WhatsApp number</label>
                <input className="input-field" value={brand.whatsappNumber ?? ''} onChange={(event) => setBrand((current) => current ? { ...current, whatsappNumber: event.target.value } : current)} />
              </div>
              <div>
                <label className="mb-1.5 block text-sm font-medium text-slate-700">Brand color</label>
                <input className="input-field" value={brand.primaryColor} onChange={(event) => setBrand((current) => current ? { ...current, primaryColor: event.target.value } : current)} />
              </div>
              <div className="flex items-center gap-4">
                <label className="flex items-center gap-2 text-sm font-medium text-slate-700">
                  <input type="checkbox" checked={brand.isListedOnMarketplace} onChange={(event) => setBrand((current) => current ? { ...current, isListedOnMarketplace: event.target.checked } : current)} />
                  Listed on marketplace
                </label>
              </div>
            </div>
            <div className="mt-5 grid gap-4 lg:grid-cols-2">
              <label className="block">
                <span className="mb-1.5 block text-sm font-medium text-slate-700">Logo upload</span>
                <input type="file" accept="image/*" onChange={(event) => uploadBrandAsset('logo', event.target.files?.[0] ?? null)} className="input-field" />
                <p className="mt-2 text-xs text-slate-500">{uploadingAsset === 'logo' ? 'Uploading…' : brand.logoUrl ? 'Logo uploaded' : 'No logo uploaded yet'}</p>
              </label>
              <label className="block">
                <span className="mb-1.5 block text-sm font-medium text-slate-700">Hero image upload</span>
                <input type="file" accept="image/*" onChange={(event) => uploadBrandAsset('hero', event.target.files?.[0] ?? null)} className="input-field" />
                <p className="mt-2 text-xs text-slate-500">{uploadingAsset === 'hero' ? 'Uploading…' : brand.heroImageUrl ? 'Hero image uploaded' : 'No hero image uploaded yet'}</p>
              </label>
            </div>
          </div>

          <div className="grid gap-6 lg:grid-cols-2">
            <div className="card p-6">
              <div className="flex items-center justify-between gap-4">
                <div>
                  <h3 className="text-base font-semibold text-slate-900">Rental payment methods</h3>
                  <p className="mt-1 text-sm text-slate-500">Configure how renters pay your company on the public booking site.</p>
                </div>
                <button onClick={saveBrandSettings} disabled={saving} className="btn-primary">
                  {saving ? 'Saving…' : 'Save payments'}
                </button>
              </div>
              <div className="mt-5 grid gap-4">
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-slate-700">AmanPay merchant ID</label>
                  <input className="input-field" value={brand.amanpayMerchantId ?? ''} onChange={(event) => setBrand((current) => current ? { ...current, amanpayMerchantId: event.target.value } : current)} />
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-slate-700">AmanPay secret key</label>
                  <input className="input-field" type="password" value={brand.amanpaySecretKey ?? ''} onChange={(event) => setBrand((current) => current ? { ...current, amanpaySecretKey: event.target.value } : current)} />
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-slate-700">PayPal business email</label>
                  <input className="input-field" type="email" value={brand.paypalEmail ?? ''} onChange={(event) => setBrand((current) => current ? { ...current, paypalEmail: event.target.value } : current)} />
                </div>
                <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4 text-sm text-slate-600">
                  If no payment method is configured, renters can still submit reservation requests and pay on pickup.
                </div>
              </div>
            </div>

            <div className="card p-6">
              <div className="flex items-center justify-between gap-4">
                <div>
                  <h3 className="text-base font-semibold text-slate-900">Custom domain</h3>
                  <p className="mt-1 text-sm text-slate-500">Point your own domain to the branded booking site.</p>
                </div>
                <button onClick={saveCustomDomain} disabled={saving || !customDomain.trim()} className="btn-primary">
                  {saving ? 'Saving…' : 'Save domain'}
                </button>
              </div>
              <div className="mt-5 space-y-4">
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-slate-700">Subdomain</label>
                  <div className="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3 text-sm text-slate-700">{brand.subdomain}.RentalDriveGo.com</div>
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-slate-700">Custom domain</label>
                  <input className="input-field" placeholder="cars.example.com" value={customDomain} onChange={(event) => setCustomDomain(event.target.value)} />
                </div>
                <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4 text-sm text-slate-600">
                  Status: {brand.customDomain ? (brand.customDomainVerified ? 'Verified' : 'Pending DNS verification') : 'Not configured'}
                </div>
                {brand.customDomain ? (
                  <button onClick={removeCustomDomain} disabled={saving} className="btn-secondary">
                    Remove custom domain
                  </button>
                ) : null}
              </div>
            </div>
          </div>
        </div>
      )}

      {contractSettings && (
        <div className="card p-6">
          <div className="flex items-center justify-between">
            <h3 className="text-base font-semibold text-slate-900">Contract and driver policies</h3>
            <button onClick={saveContractSettings} disabled={saving} className="btn-primary">
              {saving ? 'Saving…' : 'Save policies'}
            </button>
          </div>
          <div className="mt-5 grid gap-4 lg:grid-cols-2">
            <div>
              <label className="mb-1.5 block text-sm font-medium text-slate-700">Fuel policy type</label>
              <select className="input-field" value={contractSettings.fuelPolicyType} onChange={(event) => setContractSettings((current) => current ? { ...current, fuelPolicyType: event.target.value } : current)}>
                {['FULL_TO_FULL', 'FULL_TO_EMPTY', 'SAME_TO_SAME', 'PREPAID', 'FREE'].map((option) => <option key={option} value={option}>{option}</option>)}
              </select>
            </div>
            <div>
              <label className="mb-1.5 block text-sm font-medium text-slate-700">Additional driver charge</label>
              <select className="input-field" value={contractSettings.additionalDriverCharge} onChange={(event) => setContractSettings((current) => current ? { ...current, additionalDriverCharge: event.target.value as ContractSettings['additionalDriverCharge'] } : current)}>
                {['FREE', 'PER_DAY', 'FLAT'].map((option) => <option key={option} value={option}>{option}</option>)}
              </select>
            </div>
            <div>
              <label className="mb-1.5 block text-sm font-medium text-slate-700">Daily driver rate</label>
              <input type="number" className="input-field" value={contractSettings.additionalDriverDailyRate} onChange={(event) => setContractSettings((current) => current ? { ...current, additionalDriverDailyRate: Number(event.target.value) } : current)} />
            </div>
            <div>
              <label className="mb-1.5 block text-sm font-medium text-slate-700">Flat driver rate</label>
              <input type="number" className="input-field" value={contractSettings.additionalDriverFlatRate} onChange={(event) => setContractSettings((current) => current ? { ...current, additionalDriverFlatRate: Number(event.target.value) } : current)} />
            </div>
            <div className="lg:col-span-2">
              <label className="mb-1.5 block text-sm font-medium text-slate-700">Fuel policy note</label>
              <textarea className="input-field min-h-24" value={contractSettings.fuelPolicyNote ?? ''} onChange={(event) => setContractSettings((current) => current ? { ...current, fuelPolicyNote: event.target.value } : current)} />
            </div>
            <div className="lg:col-span-2">
              <label className="mb-1.5 block text-sm font-medium text-slate-700">Damage policy</label>
              <textarea className="input-field min-h-24" value={contractSettings.damagePolicy ?? ''} onChange={(event) => setContractSettings((current) => current ? { ...current, damagePolicy: event.target.value } : current)} />
            </div>
          </div>
        </div>
      )}

      <div className="grid gap-6 xl:grid-cols-2">
        <div className="card p-6">
          <h3 className="text-base font-semibold text-slate-900">Insurance policies</h3>
          <div className="mt-5 space-y-3">
            {insurancePolicies.map((policy) => (
              <div key={policy.id} className="flex items-center justify-between rounded-2xl border border-slate-200 px-4 py-3 text-sm">
                <div>
                  <p className="font-medium text-slate-900">{policy.name}</p>
                  <p className="text-slate-500">{policy.type} · {policy.chargeType} · {policy.chargeValue}</p>
                </div>
                <button onClick={() => toggleInsurance(policy)} className={policy.isActive ? 'badge-green' : 'badge-gray'}>
                  {policy.isActive ? 'Active' : 'Inactive'}
                </button>
              </div>
            ))}
            {insurancePolicies.length === 0 && <div className="text-sm text-slate-400">No insurance policies configured yet.</div>}
          </div>

          <div className="mt-5 grid gap-3 sm:grid-cols-2">
            <input className="input-field" placeholder="Policy name" value={newInsurance.name} onChange={(event) => setNewInsurance((current) => ({ ...current, name: event.target.value }))} />
            <select className="input-field" value={newInsurance.type} onChange={(event) => setNewInsurance((current) => ({ ...current, type: event.target.value }))}>
              {['BASIC', 'FULL', 'CDW', 'SCDW', 'THEFT', 'THIRD_PARTY', 'ROADSIDE', 'PERSONAL', 'CUSTOM'].map((option) => <option key={option} value={option}>{option}</option>)}
            </select>
            <select className="input-field" value={newInsurance.chargeType} onChange={(event) => setNewInsurance((current) => ({ ...current, chargeType: event.target.value }))}>
              {['PER_DAY', 'PER_RENTAL', 'PERCENTAGE_OF_RENTAL'].map((option) => <option key={option} value={option}>{option}</option>)}
            </select>
            <input type="number" className="input-field" placeholder="Charge value" value={newInsurance.chargeValue} onChange={(event) => setNewInsurance((current) => ({ ...current, chargeValue: Number(event.target.value) }))} />
          </div>
          <div className="mt-3 flex items-center gap-4 text-sm">
            <label className="flex items-center gap-2"><input type="checkbox" checked={newInsurance.isRequired} onChange={(event) => setNewInsurance((current) => ({ ...current, isRequired: event.target.checked }))} /> Required</label>
            <button onClick={createInsurance} disabled={saving} className="btn-primary">{saving ? 'Saving…' : 'Add policy'}</button>
          </div>
        </div>

        <div className="card p-6">
          <h3 className="text-base font-semibold text-slate-900">Pricing rules</h3>
          <div className="mt-5 space-y-3">
            {pricingRules.map((rule) => (
              <div key={rule.id} className="flex items-center justify-between rounded-2xl border border-slate-200 px-4 py-3 text-sm">
                <div>
                  <p className="font-medium text-slate-900">{rule.name}</p>
                  <p className="text-slate-500">{rule.type} · {rule.condition} {rule.conditionValue} · {rule.adjustmentType} {rule.adjustmentValue}</p>
                </div>
                <button onClick={() => toggleRule(rule)} className={rule.isActive ? 'badge-green' : 'badge-gray'}>
                  {rule.isActive ? 'Active' : 'Inactive'}
                </button>
              </div>
            ))}
            {pricingRules.length === 0 && <div className="text-sm text-slate-400">No pricing rules configured yet.</div>}
          </div>

          <div className="mt-5 grid gap-3 sm:grid-cols-2">
            <input className="input-field" placeholder="Rule name" value={newRule.name} onChange={(event) => setNewRule((current) => ({ ...current, name: event.target.value }))} />
            <select className="input-field" value={newRule.type} onChange={(event) => setNewRule((current) => ({ ...current, type: event.target.value }))}>
              {['SURCHARGE', 'DISCOUNT'].map((option) => <option key={option} value={option}>{option}</option>)}
            </select>
            <select className="input-field" value={newRule.condition} onChange={(event) => setNewRule((current) => ({ ...current, condition: event.target.value }))}>
              {['AGE_LESS_THAN', 'AGE_GREATER_THAN', 'LICENSE_YEARS_LESS_THAN', 'LICENSE_YEARS_GREATER_THAN'].map((option) => <option key={option} value={option}>{option}</option>)}
            </select>
            <input type="number" className="input-field" value={newRule.conditionValue} onChange={(event) => setNewRule((current) => ({ ...current, conditionValue: Number(event.target.value) }))} />
            <select className="input-field" value={newRule.adjustmentType} onChange={(event) => setNewRule((current) => ({ ...current, adjustmentType: event.target.value }))}>
              {['PERCENTAGE', 'FLAT_PER_DAY', 'FLAT_TOTAL'].map((option) => <option key={option} value={option}>{option}</option>)}
            </select>
            <input type="number" className="input-field" value={newRule.adjustmentValue} onChange={(event) => setNewRule((current) => ({ ...current, adjustmentValue: Number(event.target.value) }))} />
          </div>
          <div className="mt-3">
            <button onClick={createRule} disabled={saving} className="btn-primary">{saving ? 'Saving…' : 'Add rule'}</button>
          </div>
        </div>
      </div>

      {accountingSettings && (
        <div className="card p-6">
          <div className="flex items-center justify-between">
            <h3 className="text-base font-semibold text-slate-900">Accounting and exports</h3>
            <button onClick={saveAccountingSettings} disabled={saving} className="btn-primary">
              {saving ? 'Saving…' : 'Save accounting'}
            </button>
          </div>
          <div className="mt-5 grid gap-4 lg:grid-cols-2">
            <div>
              <label className="mb-1.5 block text-sm font-medium text-slate-700">Reporting period</label>
              <select className="input-field" value={accountingSettings.reportingPeriod} onChange={(event) => setAccountingSettings((current) => current ? { ...current, reportingPeriod: event.target.value } : current)}>
                {['WEEKLY', 'MONTHLY', 'QUARTERLY', 'ANNUAL'].map((option) => <option key={option} value={option}>{option}</option>)}
              </select>
            </div>
            <div>
              <label className="mb-1.5 block text-sm font-medium text-slate-700">Report format</label>
              <select className="input-field" value={accountingSettings.reportFormat} onChange={(event) => setAccountingSettings((current) => current ? { ...current, reportFormat: event.target.value } : current)}>
                {['CSV', 'PDF', 'BOTH'].map((option) => <option key={option} value={option}>{option}</option>)}
              </select>
            </div>
            <div>
              <label className="mb-1.5 block text-sm font-medium text-slate-700">Accountant name</label>
              <input className="input-field" value={accountingSettings.accountantName ?? ''} onChange={(event) => setAccountingSettings((current) => current ? { ...current, accountantName: event.target.value } : current)} />
            </div>
            <div>
              <label className="mb-1.5 block text-sm font-medium text-slate-700">Accountant email</label>
              <input className="input-field" value={accountingSettings.accountantEmail ?? ''} onChange={(event) => setAccountingSettings((current) => current ? { ...current, accountantEmail: event.target.value } : current)} />
            </div>
          </div>
          <label className="mt-4 flex items-center gap-2 text-sm font-medium text-slate-700">
            <input type="checkbox" checked={accountingSettings.autoSendReport} onChange={(event) => setAccountingSettings((current) => current ? { ...current, autoSendReport: event.target.checked } : current)} />
            Auto-send reports to the accountant
          </label>
        </div>
      )}
    </div>
  )
}
