'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import Box from '@mui/material/Box'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import CardHeader from '@mui/material/CardHeader'
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import IconButton from '@mui/material/IconButton'
import TextField from '@mui/material/TextField'
import MenuItem from '@mui/material/MenuItem'
import Switch from '@mui/material/Switch'
import FormControlLabel from '@mui/material/FormControlLabel'
import Divider from '@mui/material/Divider'
import Alert from '@mui/material/Alert'
import Chip from '@mui/material/Chip'
import Tooltip from '@mui/material/Tooltip'
import Checkbox from '@mui/material/Checkbox'
import Autocomplete from '@mui/material/Autocomplete'
import type { ClientFolder, BillingConfig, BillingType, BillingFrequency, InvoiceDelivery, RateScheduleEntry } from './types'

// ─── Constants ────────────────────────────────────────────────────────────────

const BILLING_TYPES: { value: BillingType; label: string; description: string }[] = [
  { value: 'hourly',      label: 'Hourly',         description: 'Charge by time spent — billed from logged time entries' },
  { value: 'fixed',       label: 'Fixed Fee',      description: 'One agreed amount for the entire matter' },
  { value: 'retainer',    label: 'Retainer Draw',  description: 'Time debits the retainer balance directly — no invoice' },
  { value: 'contingency', label: 'Contingency',    description: 'Fee is a percentage of the recovery amount' },
  { value: 'hybrid',      label: 'Hybrid',         description: 'Mix of fixed engagement fee + hourly for additional work' },
]

const BILLING_FREQUENCIES: { value: BillingFrequency; label: string }[] = [
  { value: 'monthly',          label: 'Monthly' },
  { value: 'bi_monthly',       label: 'Bi-Monthly (every 2 months)' },
  { value: 'quarterly',        label: 'Quarterly' },
  { value: 'as_incurred',      label: 'As Incurred (invoice each entry immediately)' },
  { value: 'upon_completion',  label: 'Upon Matter Completion' },
  { value: 'milestone',        label: 'Milestone-Based' },
]

const PAYMENT_TERMS: { value: number; label: string }[] = [
  { value: 0,  label: 'Due on Receipt' },
  { value: 7,  label: 'Net 7 days' },
  { value: 15, label: 'Net 15 days' },
  { value: 30, label: 'Net 30 days' },
  { value: 45, label: 'Net 45 days' },
  { value: 60, label: 'Net 60 days' },
]

const DELIVERY_OPTIONS: { value: InvoiceDelivery; label: string }[] = [
  { value: 'email',   label: 'Email' },
  { value: 'postal',  label: 'Post / Courier' },
  { value: 'both',    label: 'Email + Post' },
  { value: 'none',    label: 'No delivery (internal record only)' },
]

// ISO 4217 currencies — label includes code for searchability
const CURRENCIES: { code: string; name: string }[] = [
  { code: 'THB', name: 'Thai Baht' },
  { code: 'USD', name: 'US Dollar' },
  { code: 'EUR', name: 'Euro' },
  { code: 'GBP', name: 'British Pound' },
  { code: 'JPY', name: 'Japanese Yen' },
  { code: 'CNY', name: 'Chinese Yuan' },
  { code: 'HKD', name: 'Hong Kong Dollar' },
  { code: 'SGD', name: 'Singapore Dollar' },
  { code: 'AUD', name: 'Australian Dollar' },
  { code: 'CAD', name: 'Canadian Dollar' },
  { code: 'CHF', name: 'Swiss Franc' },
  { code: 'NZD', name: 'New Zealand Dollar' },
  { code: 'SEK', name: 'Swedish Krona' },
  { code: 'NOK', name: 'Norwegian Krone' },
  { code: 'DKK', name: 'Danish Krone' },
  { code: 'MYR', name: 'Malaysian Ringgit' },
  { code: 'IDR', name: 'Indonesian Rupiah' },
  { code: 'PHP', name: 'Philippine Peso' },
  { code: 'VND', name: 'Vietnamese Dong' },
  { code: 'KRW', name: 'South Korean Won' },
  { code: 'TWD', name: 'New Taiwan Dollar' },
  { code: 'INR', name: 'Indian Rupee' },
  { code: 'PKR', name: 'Pakistani Rupee' },
  { code: 'BDT', name: 'Bangladeshi Taka' },
  { code: 'LKR', name: 'Sri Lankan Rupee' },
  { code: 'AED', name: 'UAE Dirham' },
  { code: 'SAR', name: 'Saudi Riyal' },
  { code: 'QAR', name: 'Qatari Riyal' },
  { code: 'KWD', name: 'Kuwaiti Dinar' },
  { code: 'BHD', name: 'Bahraini Dinar' },
  { code: 'OMR', name: 'Omani Rial' },
  { code: 'JOD', name: 'Jordanian Dinar' },
  { code: 'EGP', name: 'Egyptian Pound' },
  { code: 'ZAR', name: 'South African Rand' },
  { code: 'NGN', name: 'Nigerian Naira' },
  { code: 'KES', name: 'Kenyan Shilling' },
  { code: 'GHS', name: 'Ghanaian Cedi' },
  { code: 'TZS', name: 'Tanzanian Shilling' },
  { code: 'UGX', name: 'Ugandan Shilling' },
  { code: 'ETB', name: 'Ethiopian Birr' },
  { code: 'MAD', name: 'Moroccan Dirham' },
  { code: 'TND', name: 'Tunisian Dinar' },
  { code: 'DZD', name: 'Algerian Dinar' },
  { code: 'BRL', name: 'Brazilian Real' },
  { code: 'MXN', name: 'Mexican Peso' },
  { code: 'ARS', name: 'Argentine Peso' },
  { code: 'CLP', name: 'Chilean Peso' },
  { code: 'COP', name: 'Colombian Peso' },
  { code: 'PEN', name: 'Peruvian Sol' },
  { code: 'UYU', name: 'Uruguayan Peso' },
  { code: 'BOB', name: 'Bolivian Boliviano' },
  { code: 'PYG', name: 'Paraguayan Guaraní' },
  { code: 'VES', name: 'Venezuelan Bolívar' },
  { code: 'RUB', name: 'Russian Ruble' },
  { code: 'UAH', name: 'Ukrainian Hryvnia' },
  { code: 'PLN', name: 'Polish Zloty' },
  { code: 'CZK', name: 'Czech Koruna' },
  { code: 'HUF', name: 'Hungarian Forint' },
  { code: 'RON', name: 'Romanian Leu' },
  { code: 'BGN', name: 'Bulgarian Lev' },
  { code: 'HRK', name: 'Croatian Kuna' },
  { code: 'RSD', name: 'Serbian Dinar' },
  { code: 'TRY', name: 'Turkish Lira' },
  { code: 'ILS', name: 'Israeli New Shekel' },
  { code: 'IRR', name: 'Iranian Rial' },
  { code: 'IQD', name: 'Iraqi Dinar' },
  { code: 'LBP', name: 'Lebanese Pound' },
  { code: 'SYP', name: 'Syrian Pound' },
  { code: 'YER', name: 'Yemeni Rial' },
  { code: 'AFN', name: 'Afghan Afghani' },
  { code: 'PKR', name: 'Pakistani Rupee' },
  { code: 'NPR', name: 'Nepalese Rupee' },
  { code: 'BTN', name: 'Bhutanese Ngultrum' },
  { code: 'MMK', name: 'Myanmar Kyat' },
  { code: 'KHR', name: 'Cambodian Riel' },
  { code: 'LAK', name: 'Lao Kip' },
  { code: 'MNT', name: 'Mongolian Tögrög' },
  { code: 'KZT', name: 'Kazakhstani Tenge' },
  { code: 'UZS', name: 'Uzbekistani Som' },
  { code: 'GEL', name: 'Georgian Lari' },
  { code: 'AMD', name: 'Armenian Dram' },
  { code: 'AZN', name: 'Azerbaijani Manat' },
  { code: 'BYN', name: 'Belarusian Ruble' },
  { code: 'MDL', name: 'Moldovan Leu' },
  { code: 'ALL', name: 'Albanian Lek' },
  { code: 'MKD', name: 'Macedonian Denar' },
  { code: 'BAM', name: 'Bosnia-Herzegovina Mark' },
  { code: 'ISK', name: 'Icelandic Króna' },
  { code: 'MOP', name: 'Macanese Pataca' },
  { code: 'BND', name: 'Brunei Dollar' },
  { code: 'FJD', name: 'Fijian Dollar' },
  { code: 'PGK', name: 'Papua New Guinean Kina' },
  { code: 'SBD', name: 'Solomon Islands Dollar' },
  { code: 'WST', name: 'Samoan Tala' },
  { code: 'TOP', name: 'Tongan Paʻanga' },
  { code: 'VUV', name: 'Vanuatu Vatu' },
]

// ─── Default config ────────────────────────────────────────────────────────

function defaultConfig(folder: ClientFolder): BillingConfig {
  const existing = folder.billingConfig
  if (existing) {
    // Migrate legacy single billingType → billingTypes array
    if (!existing.billingTypes || existing.billingTypes.length === 0) {
      return {
        ...existing,
        billingTypes: existing.billingType ? [existing.billingType] : ['hourly'],
        currency: existing.currency ?? folder.currency ?? 'THB',
      }
    }
    return { ...existing, currency: existing.currency ?? folder.currency ?? 'THB' }
  }
  return {
    billingTypes: ['hourly'],
    currency: folder.currency ?? 'THB',
    defaultHourlyRate: 5000,
    rateSchedule: [],
    retainerRequired: true,
    retainerAmount: folder.retainerThreshold ?? 20000,
    retainerThreshold: folder.retainerThreshold ?? 20000,
    autoReplenish: false,
    billingFrequency: 'monthly',
    billingDayOfMonth: 1,
    paymentTermsDays: 30,
    vatExempt: false,
    vatRate: 0.07,
    invoiceDelivery: 'email',
    billingNotes: '',
  }
}

// ─── Section wrapper ──────────────────────────────────────────────────────────

function Section({ title, icon, subtitle, children }: { title: string; icon: string; subtitle?: string; children: React.ReactNode }) {
  return (
    <Card>
      <CardHeader
        title={title}
        subheader={subtitle}
        titleTypographyProps={{ variant: 'subtitle1', fontWeight: 700 }}
        subheaderTypographyProps={{ variant: 'caption' }}
        avatar={<Box sx={{ width: 32, height: 32, borderRadius: 1.5, bgcolor: '#E8F7F7', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <i className={icon} style={{ color: '#0D9394', fontSize: '1.1rem' }} />
        </Box>}
        sx={{ pb: 1 }}
      />
      <Divider />
      <CardContent sx={{ pt: 2.5 }}>{children}</CardContent>
    </Card>
  )
}

// ─── Rate Schedule ────────────────────────────────────────────────────────────

function RateSchedule({
  entries,
  currency,
  onChange,
}: {
  entries: RateScheduleEntry[]
  currency: string
  onChange: (entries: RateScheduleEntry[]) => void
}) {
  const empty = (): RateScheduleEntry => ({ attorney: '', title: '', rate: 0 })

  function update(i: number, field: keyof RateScheduleEntry, value: string | number) {
    const next = entries.map((e, idx) => idx === i ? { ...e, [field]: value } : e)
    onChange(next)
  }
  function remove(i: number) { onChange(entries.filter((_, idx) => idx !== i)) }
  function add()              { onChange([...entries, empty()]) }

  return (
    <Box>
      <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 1.5 }}>
        <Typography variant='body2' sx={{ fontWeight: 600 }}>Timekeeper Rate Schedule</Typography>
        <Button size='small' startIcon={<i className='ri-add-line' />} onClick={add}>Add Timekeeper</Button>
      </Box>

      {entries.length === 0 ? (
        <Box sx={{ p: 2, border: '1px dashed', borderColor: 'divider', borderRadius: 1.5, textAlign: 'center' }}>
          <Typography variant='caption' color='text.disabled'>
            No individual rates set — all time logged at the default hourly rate above
          </Typography>
        </Box>
      ) : (
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
          {entries.map((e, i) => (
            <Box key={i} sx={{ display: 'flex', gap: 1.5, alignItems: 'center' }}>
              <TextField
                label='Attorney / Timekeeper' size='small' value={e.attorney}
                onChange={ev => update(i, 'attorney', ev.target.value)}
                sx={{ flex: 2 }}
              />
              <TextField
                label='Title / Role' size='small' value={e.title ?? ''}
                onChange={ev => update(i, 'title', ev.target.value)}
                sx={{ flex: 1.5 }}
                placeholder='e.g. Partner, Associate'
              />
              <TextField
                label={`Rate (${currency}/hr)`} size='small' type='number' value={e.rate || ''}
                onChange={ev => update(i, 'rate', parseFloat(ev.target.value) || 0)}
                sx={{ flex: 1 }}
              />
              <Tooltip title='Remove'>
                <IconButton size='small' onClick={() => remove(i)} color='error'>
                  <i className='ri-delete-bin-line' style={{ fontSize: '1rem' }} />
                </IconButton>
              </Tooltip>
            </Box>
          ))}
        </Box>
      )}
    </Box>
  )
}

// ─── Main component ───────────────────────────────────────────────────────────

export default function BillingSettingsView({ folder: initial, lang }: { folder: ClientFolder; lang: string }) {
  const router  = useRouter()
  const [config, setConfig] = useState<BillingConfig>(() => defaultConfig(initial))
  const [saving, setSaving] = useState(false)
  const [saved,  setSaved]  = useState(false)
  const [error,  setError]  = useState<string | null>(null)
  const [newScheduleDate, setNewScheduleDate] = useState('')

  function set<K extends keyof BillingConfig>(key: K, value: BillingConfig[K]) {
    setConfig(c => ({ ...c, [key]: value }))
    setSaved(false)
  }

  function toggleBillingType(type: BillingType) {
    const current = config.billingTypes ?? []
    const next = current.includes(type)
      ? current.filter(t => t !== type)
      : [...current, type]
    if (next.length === 0) return // must have at least one
    set('billingTypes', next)
    setSaved(false)
  }

  function addScheduleDate() {
    if (!newScheduleDate) return
    const existing = config.billingScheduleDates ?? []
    if (existing.includes(newScheduleDate)) return
    set('billingScheduleDates', [...existing, newScheduleDate].sort())
    setNewScheduleDate('')
  }

  function removeScheduleDate(date: string) {
    set('billingScheduleDates', (config.billingScheduleDates ?? []).filter(d => d !== date))
  }

  async function save() {
    setSaving(true); setError(null); setSaved(false)
    try {
      const res = await fetch(`/api/clients/${initial._id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ billingConfig: { ...config, updatedAt: new Date().toISOString() } }),
      })
      if (!res.ok) throw new Error((await res.json().catch(() => ({}))).message ?? 'Save failed')
      setSaved(true)
    } catch (e: any) { setError(e.message) }
    finally { setSaving(false) }
  }

  const currency      = config.currency ?? initial.currency ?? 'THB'
  const billingTypes  = config.billingTypes ?? []
  const hasHourly     = billingTypes.includes('hourly') || billingTypes.includes('hybrid')
  const hasFixed      = billingTypes.includes('fixed')
  const selectedCurr  = CURRENCIES.find(c => c.code === currency) ?? null

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>

      {/* ── Client identity banner ── */}
      <Card sx={{ bgcolor: '#0D9394', color: 'white', borderRadius: 2 }}>
        <CardContent sx={{ py: 2, '&:last-child': { pb: 2 } }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
            <Box sx={{ width: 44, height: 44, borderRadius: '50%', bgcolor: 'rgba(255,255,255,0.2)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <i className='ri-user-line' style={{ fontSize: '1.4rem' }} />
            </Box>
            <Box>
              <Typography variant='h6' sx={{ fontWeight: 700, lineHeight: 1.2 }}>{initial.displayName}</Typography>
              <Typography variant='caption' sx={{ opacity: 0.85 }}>
                {initial.folderNumber} · Billing &amp; Fee Configuration
              </Typography>
            </Box>
            <Box sx={{ ml: 'auto' }}>
              <Button
                size='small' variant='text'
                startIcon={<i className='ri-arrow-left-line' />}
                onClick={() => router.push(`/${lang}/clients/${initial._id}`)}
                sx={{ color: 'white', opacity: 0.85, '&:hover': { opacity: 1, bgcolor: 'rgba(255,255,255,0.1)' } }}
              >
                Back to {initial.displayName}
              </Button>
            </Box>
          </Box>
        </CardContent>
      </Card>

      {/* Note about matter-level override */}
      <Alert severity='info' icon={<i className='ri-information-line' />} sx={{ py: 0.5 }}>
        These are <strong>client-level defaults</strong>. Each individual matter can override the billing type, rate, and currency when created or edited.
      </Alert>

      {error && <Alert severity='error' onClose={() => setError(null)}>{error}</Alert>}

      {/* Save row top */}
      <Box sx={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', gap: 1.5 }}>
        {saved && <Chip label='Saved' size='small' sx={{ bgcolor: '#EEFBE5', color: '#71DD37', fontWeight: 600 }} />}
        <Button
          variant='contained' onClick={save} disabled={saving}
          startIcon={<i className={saving ? 'ri-loader-4-line' : 'ri-save-line'} />}
          sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}
        >
          {saving ? 'Saving…' : 'Save Settings'}
        </Button>
      </Box>

      {/* ── 1. Billing Types (multi-select) ── */}
      <Section title='Billing Types' icon='ri-scales-2-line' subtitle='Select all that apply — a client can have multiple arrangements across different matters'>
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: 1.5 }}>
            {BILLING_TYPES.map(bt => {
              const selected = billingTypes.includes(bt.value)
              return (
                <Box
                  key={bt.value}
                  onClick={() => toggleBillingType(bt.value)}
                  sx={{
                    p: 2, borderRadius: 2, cursor: 'pointer', border: '2px solid', position: 'relative',
                    borderColor: selected ? '#0D9394' : 'divider',
                    bgcolor: selected ? '#E8F7F7' : 'background.paper',
                    transition: 'all 0.15s',
                    '&:hover': { borderColor: '#0D9394', bgcolor: '#F0FAFA' },
                  }}
                >
                  <Box sx={{ position: 'absolute', top: 8, right: 8 }}>
                    <Checkbox
                      checked={selected}
                      onChange={() => toggleBillingType(bt.value)}
                      onClick={e => e.stopPropagation()}
                      size='small'
                      sx={{ p: 0, color: selected ? '#0D9394' : 'text.disabled', '&.Mui-checked': { color: '#0D9394' } }}
                    />
                  </Box>
                  <Typography variant='body2' sx={{ fontWeight: 700, mb: 0.5, pr: 3, color: selected ? '#0D4040' : 'text.primary' }}>{bt.label}</Typography>
                  <Typography variant='caption' sx={{ lineHeight: 1.4, color: selected ? '#1A5555' : 'text.secondary' }}>{bt.description}</Typography>
                </Box>
              )
            })}
          </Box>

          {billingTypes.length > 1 && (
            <Box sx={{ p: 1.5, bgcolor: '#F8F7FF', borderRadius: 1.5, border: '1px solid', borderColor: '#E0DCF8' }}>
              <Typography variant='caption' color='#7C6AF7'>
                <strong>Multi-type arrangement:</strong> {billingTypes.map(t => BILLING_TYPES.find(bt => bt.value === t)?.label).join(' + ')}.
                Each matter records which type applies.
              </Typography>
            </Box>
          )}
        </Box>
      </Section>

      {/* ── 2. Currency ── */}
      <Section title='Billing Currency' icon='ri-exchange-dollar-line' subtitle='Default currency for invoices — can be overridden per matter'>
        <Autocomplete
          options={CURRENCIES}
          value={selectedCurr}
          getOptionLabel={opt => `${opt.code} — ${opt.name}`}
          isOptionEqualToValue={(a, b) => a.code === b.code}
          onChange={(_, val) => set('currency', val?.code ?? 'THB')}
          renderInput={params => (
            <TextField {...params} label='Currency' size='small' sx={{ maxWidth: 360 }}
              helperText='Type to search by code or currency name'
            />
          )}
          renderOption={(props, opt) => (
            <Box component='li' {...props} sx={{ display: 'flex', gap: 1.5 }}>
              <Typography variant='body2' sx={{ fontWeight: 700, minWidth: 48, color: '#0D9394' }}>{opt.code}</Typography>
              <Typography variant='body2' color='text.secondary'>{opt.name}</Typography>
            </Box>
          )}
          sx={{ maxWidth: 360 }}
        />
      </Section>

      {/* ── 3. Rates ── */}
      {hasHourly && (
        <Section title='Rate Schedule' icon='ri-money-dollar-circle-line' subtitle='Default rate applies when no per-timekeeper rate is set'>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
            <Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-end' }}>
              <TextField
                label={`Default Hourly Rate (${currency})`}
                type='number'
                value={config.defaultHourlyRate || ''}
                onChange={e => set('defaultHourlyRate', parseFloat(e.target.value) || 0)}
                size='small'
                sx={{ width: 220 }}
                helperText='Applied to all time entries unless overridden below'
              />
            </Box>
            <Divider />
            <RateSchedule
              entries={config.rateSchedule}
              currency={currency}
              onChange={entries => set('rateSchedule', entries)}
            />
          </Box>
        </Section>
      )}

      {hasFixed && !hasHourly && (
        <Section title='Fixed Fee' icon='ri-money-dollar-circle-line' subtitle='Set on each matter individually — this section records the policy'>
          <Box sx={{ p: 2, bgcolor: 'action.hover', borderRadius: 1.5 }}>
            <Typography variant='body2' color='text.secondary'>
              Fixed fee amounts are set per matter when the matter is created. Use the billing notes below to record your fixed fee policy for this client (e.g. standard fee schedule, volume discounts).
            </Typography>
          </Box>
        </Section>
      )}

      {/* ── 4. Retainer Maintenance ── */}
      <Section title='Retainer Maintenance' icon='ri-safe-2-line' subtitle='Rules for maintaining the client retainer balance'>
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2.5 }}>
          <FormControlLabel
            control={<Switch checked={config.retainerRequired} onChange={e => set('retainerRequired', e.target.checked)} />}
            label={
              <Box>
                <Typography variant='body2' sx={{ fontWeight: 600 }}>Retainer Required</Typography>
                <Typography variant='caption' color='text.secondary'>Client must maintain an advance retainer balance</Typography>
              </Box>
            }
          />

          {config.retainerRequired && (
            <>
              <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}>
                <TextField
                  label={`Required Retainer Amount (${currency})`}
                  type='number'
                  value={config.retainerAmount || ''}
                  onChange={e => set('retainerAmount', parseFloat(e.target.value) || 0)}
                  size='small'
                  sx={{ flex: '1 1 200px' }}
                  helperText='Target replenishment level'
                />
                <TextField
                  label={`Minimum Balance Threshold (${currency})`}
                  type='number'
                  value={config.retainerThreshold || ''}
                  onChange={e => set('retainerThreshold', parseFloat(e.target.value) || 0)}
                  size='small'
                  sx={{ flex: '1 1 200px' }}
                  helperText='Alert triggered when balance falls below this'
                />
              </Box>

              <FormControlLabel
                control={<Switch checked={config.autoReplenish} onChange={e => set('autoReplenish', e.target.checked)} />}
                label={
                  <Box>
                    <Typography variant='body2' sx={{ fontWeight: 600 }}>Auto Replenishment Reminder</Typography>
                    <Typography variant='caption' color='text.secondary'>Automatically flag for top-up request when balance drops below threshold</Typography>
                  </Box>
                }
              />
            </>
          )}
        </Box>
      </Section>

      {/* ── 5. Billing Schedule ── */}
      <Section title='Billing Schedule' icon='ri-calendar-schedule-line' subtitle='When to generate and send invoices — counsel can set specific dates'>
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2.5 }}>
          <TextField
            select
            label='Billing Frequency'
            value={config.billingFrequency}
            onChange={e => set('billingFrequency', e.target.value as BillingFrequency)}
            size='small'
            sx={{ maxWidth: 360 }}
          >
            {BILLING_FREQUENCIES.map(f => <MenuItem key={f.value} value={f.value}>{f.label}</MenuItem>)}
          </TextField>

          {(config.billingFrequency === 'monthly' || config.billingFrequency === 'bi_monthly') && (
            <TextField
              label='Billing Day of Month'
              type='number'
              value={config.billingDayOfMonth ?? 1}
              onChange={e => {
                const v = Math.min(28, Math.max(1, parseInt(e.target.value) || 1))
                set('billingDayOfMonth', v)
              }}
              size='small'
              sx={{ width: 180 }}
              inputProps={{ min: 1, max: 28 }}
              helperText='Day of the month invoices are generated (1–28)'
            />
          )}

          <Divider />

          {/* Manual schedule */}
          <Box>
            <Typography variant='body2' sx={{ fontWeight: 600, mb: 0.5 }}>Next Billing Date</Typography>
            <Typography variant='caption' color='text.secondary' sx={{ display: 'block', mb: 1 }}>
              Counsel-set date — overrides the frequency above for the next invoice run
            </Typography>
            <TextField
              type='date'
              value={config.nextBillingDate ?? ''}
              onChange={e => set('nextBillingDate', e.target.value || undefined)}
              size='small'
              sx={{ width: 200 }}
              InputLabelProps={{ shrink: true }}
              label='Next Invoice Date'
            />
          </Box>

          <Box>
            <Typography variant='body2' sx={{ fontWeight: 600, mb: 0.5 }}>Scheduled Billing Dates</Typography>
            <Typography variant='caption' color='text.secondary' sx={{ display: 'block', mb: 1.5 }}>
              Add specific future dates for milestone or agreed billing events
            </Typography>
            <Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-end', mb: 1.5 }}>
              <TextField
                type='date'
                value={newScheduleDate}
                onChange={e => setNewScheduleDate(e.target.value)}
                size='small'
                label='Add Date'
                InputLabelProps={{ shrink: true }}
                sx={{ width: 200 }}
              />
              <Button
                variant='outlined' size='small'
                onClick={addScheduleDate}
                disabled={!newScheduleDate}
                startIcon={<i className='ri-add-line' />}
                sx={{ borderColor: '#0D9394', color: '#0D9394' }}
              >
                Add
              </Button>
            </Box>
            {(config.billingScheduleDates ?? []).length > 0 ? (
              <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
                {(config.billingScheduleDates ?? []).map(d => (
                  <Chip
                    key={d}
                    label={new Date(d + 'T00:00:00').toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })}
                    size='small'
                    onDelete={() => removeScheduleDate(d)}
                    sx={{ bgcolor: '#E8F7F7', color: '#0D5E5F', fontWeight: 500 }}
                    deleteIcon={<i className='ri-close-line' style={{ fontSize: '0.85rem' }} />}
                  />
                ))}
              </Box>
            ) : (
              <Typography variant='caption' color='text.disabled'>No specific dates set</Typography>
            )}
          </Box>

          <Divider />

          <TextField
            select
            label='Payment Terms'
            value={config.paymentTermsDays}
            onChange={e => set('paymentTermsDays', parseInt(e.target.value))}
            size='small'
            sx={{ maxWidth: 220 }}
            helperText='Due date = invoice date + payment terms'
          >
            {PAYMENT_TERMS.map(t => <MenuItem key={t.value} value={t.value}>{t.label}</MenuItem>)}
          </TextField>
        </Box>
      </Section>

      {/* ── 6. VAT & Tax ── */}
      <Section title='VAT & Tax' icon='ri-government-line' subtitle='Thailand 7% VAT applies by default — override here if the client or engagement is exempt'>
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          <FormControlLabel
            control={<Switch checked={config.vatExempt} onChange={e => set('vatExempt', e.target.checked)} />}
            label={
              <Box>
                <Typography variant='body2' sx={{ fontWeight: 600 }}>VAT Exempt</Typography>
                <Typography variant='caption' color='text.secondary'>Do not apply VAT to invoices for this client</Typography>
              </Box>
            }
          />

          {!config.vatExempt && (
            <Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-end', flexWrap: 'wrap' }}>
              <TextField
                label='VAT Rate'
                type='number'
                value={(config.vatRate * 100).toFixed(1)}
                onChange={e => set('vatRate', parseFloat(e.target.value) / 100 || 0.07)}
                size='small'
                sx={{ width: 140 }}
                InputProps={{ endAdornment: <Typography variant='caption' color='text.disabled' sx={{ ml: 0.5 }}>%</Typography> }}
                helperText='Default: 7%'
              />
              <TextField
                label='Client VAT Reg. Number (optional)'
                value={config.vatRegNumber ?? ''}
                onChange={e => set('vatRegNumber', e.target.value)}
                size='small'
                sx={{ flex: '1 1 240px', maxWidth: 360 }}
                helperText='Printed on invoices if provided'
              />
            </Box>
          )}
        </Box>
      </Section>

      {/* ── 7. Invoice Delivery ── */}
      <Section title='Invoice Delivery' icon='ri-send-plane-line' subtitle='How invoices are delivered to the client'>
        <TextField
          select
          label='Delivery Method'
          value={config.invoiceDelivery}
          onChange={e => set('invoiceDelivery', e.target.value as InvoiceDelivery)}
          size='small'
          sx={{ maxWidth: 280 }}
        >
          {DELIVERY_OPTIONS.map(o => <MenuItem key={o.value} value={o.value}>{o.label}</MenuItem>)}
        </TextField>
      </Section>

      {/* ── 8. Billing Notes ── */}
      <Section title='Billing Instructions' icon='ri-sticky-note-line' subtitle='Internal notes on billing arrangements, special terms, or escalation policy'>
        <TextField
          multiline
          rows={4}
          fullWidth
          value={config.billingNotes ?? ''}
          onChange={e => set('billingNotes', e.target.value)}
          placeholder={`e.g. Client negotiated 10% discount on hourly rate for matters exceeding 100 hours.\nInvoices must be sent to accounts@clientcompany.com with a copy to the CFO.\nDo not invoice without partner approval for any amount over THB 500,000.`}
          size='small'
        />
      </Section>

      {/* Save row bottom */}
      <Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 1.5, pb: 2 }}>
        {saved && <Chip label='Settings saved' size='small' sx={{ bgcolor: '#EEFBE5', color: '#71DD37', fontWeight: 600 }} />}
        {error && <Alert severity='error' sx={{ py: 0 }}>{error}</Alert>}
        <Button
          variant='contained' onClick={save} disabled={saving}
          startIcon={<i className={saving ? 'ri-loader-4-line' : 'ri-save-line'} />}
          sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}
        >
          {saving ? 'Saving…' : 'Save Settings'}
        </Button>
      </Box>

    </Box>
  )
}
