'use client'

import { useState, useEffect, useRef } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import axios from 'axios'
import { toast } from 'sonner'
import { Settings, Save, Plus, Trash2, Globe, Calendar, Users, Shield, Route, X, UserPlus, UserMinus, Building2, Building, UserCog, Check } from 'lucide-react'
import { Button, Card, CardHeader, CardTitle, CardContent, Toggle, Input, Alert, Tabs, PageHeader, SectionDivider, Select } from '@/components/ui/components'

export default function ConfigurationPage() {
  const qc = useQueryClient()
  const [tab, setTab] = useState('payments')
  const [changes, setChanges] = useState<Record<string, string>>({})

  const { data, isLoading } = useQuery({
    queryKey: ['configuration'],
    queryFn: () => axios.get('/api/configuration').then(r => r.data.data),
  })

  const { data: currencies } = useQuery({
    queryKey: ['configuration-currencies'],
    queryFn: () => axios.get('/api/configuration?sub=currencies').then(r => r.data.data),
  })

  const { data: holidays } = useQuery({
    queryKey: ['configuration-holidays'],
    queryFn: () => axios.get('/api/configuration?sub=holidays').then(r => r.data.data),
  })

  const saveMutation = useMutation({
    mutationFn: (payload: any) => axios.patch('/api/configuration', payload),
    onSuccess: () => {
      toast.success('Configuration saved successfully')
      qc.invalidateQueries({ queryKey: ['configuration'] })
      setChanges({})
    },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed to save'),
  })

  const currencyMutation = useMutation({
    mutationFn: (payload: any) => axios.post('/api/configuration', { action: 'update-currency', ...payload }),
    onSuccess: () => { toast.success('Currency updated'); qc.invalidateQueries({ queryKey: ['configuration-currencies'] }) },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed to update currency'),
  })

  const holidayMutation = useMutation({
    mutationFn: (payload: any) => axios.post('/api/configuration', { action: 'add-holiday', ...payload }),
    onSuccess: () => { toast.success('Holiday added'); qc.invalidateQueries({ queryKey: ['configuration-holidays'] }) },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed to add holiday'),
  })

  // configs is array from API: { configs: [...], grouped: {...} }
  const configsArr: any[] = data?.configs ?? []
  const configs: Record<string, string> = {}
  configsArr.forEach((c: any) => { configs[c.key] = c.value })

  function getVal(key: string) { return changes[key] ?? configs[key] ?? '' }
  function getBool(key: string) { return (changes[key] ?? configs[key]) === 'true' }
  function setVal(key: string, val: string) { setChanges(prev => ({ ...prev, [key]: val })) }
  function setBool(key: string, val: boolean) { setVal(key, val ? 'true' : 'false') }

  const hasChanges = Object.keys(changes).length > 0

  const tabs = [
    { id: 'payments',       label: 'Payments' },
    { id: 'loans',          label: 'Loans' },
    { id: 'notifications',  label: 'Notifications' },
    { id: 'features',       label: 'Features' },
    { id: 'financial',      label: 'Financial Year' },
    { id: 'currencies',     label: 'Currencies' },
    { id: 'holidays',       label: 'Holidays' },
    { id: 'user-groups',    label: 'Groups & Roles' },
    { id: 'access-control', label: 'Access Control' },
    { id: 'approval-routing', label: 'Approval Routing' },
    { id: 'company-profile', label: 'Company Profile' },
    { id: 'branches',       label: 'Branches' },
  ]

  if (isLoading) return <div className="p-6 text-muted-foreground">Loading configuration...</div>

  return (
    <div className="p-6 space-y-5 max-w-screen-xl mx-auto">
      <PageHeader
        title="System Configuration"
        description="Manage all system settings and toggles"
        icon={<Settings className="w-6 h-6"/>}
        actions={
          hasChanges ? (
            <Button icon={<Save className="w-4 h-4"/>} loading={saveMutation.isPending}
              onClick={() => saveMutation.mutate(changes)}>
              Save {Object.keys(changes).length} Change{Object.keys(changes).length > 1 ? 's' : ''}
            </Button>
          ) : undefined
        }
      />

      {hasChanges && <Alert variant="warning">You have {Object.keys(changes).length} unsaved change(s). Click <strong>Save</strong> to apply.</Alert>}

      <Tabs tabs={tabs} active={tab} onChange={setTab}/>

      {tab === 'payments' && (
        <Card>
          <CardHeader><CardTitle>Payment Allocation</CardTitle></CardHeader>
          <CardContent className="space-y-4">
            <div>
              <label className="block text-sm font-medium mb-1.5">Payment Allocation Order</label>
              <p className="text-xs text-muted-foreground mb-2">Controls how incoming repayments are allocated.</p>
              <Input value={getVal('payment_allocation_order') || 'PENALTY,INTEREST,PRINCIPAL,FEES'} onChange={e => setVal('payment_allocation_order', e.target.value)} hint="Comma-separated: PENALTY,INTEREST,PRINCIPAL,FEES"/>
            </div>
            <Toggle label="Clear Arrears First" description="Arrears instalments are cleared before the current instalment" checked={getBool('clear_arrears_first')} onChange={v => setBool('clear_arrears_first', v)}/>
            <Toggle label="Allow Excess Payment" description="Accept payments greater than the outstanding balance" checked={getBool('allow_excess_payment')} onChange={v => setBool('allow_excess_payment', v)}/>
            <Toggle label="FOSA Auto-Debit Enabled" description="Automatically debit FOSA accounts for loan repayments" checked={getBool('fosa_auto_debit')} onChange={v => setBool('fosa_auto_debit', v)}/>
          </CardContent>
        </Card>
      )}

      {tab === 'loans' && (
        <div className="space-y-4">
          <Card>
            <CardHeader><CardTitle>Loan Processing</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <Toggle label="Maker-Checker Enabled" description="All loan actions require a second user to approve" checked={getBool('loans.maker_checker')} onChange={v => setBool('loans.maker_checker', v)}/>
              <Toggle label="Penalty Enabled" description="Apply penalties on overdue loans" checked={getBool('loans.penalty_enabled')} onChange={v => setBool('loans.penalty_enabled', v)}/>
              <Toggle label="Auto-Disburse Approved Loans" description="Automatically disburse loans upon final approval" checked={getBool('loans.auto_disburse')} onChange={v => setBool('loans.auto_disburse', v)}/>
              <Toggle label="Top-Up Allowed" description="Allow members to top up existing loans" checked={getBool('loans.topup_allowed')} onChange={v => setBool('loans.topup_allowed', v)}/>
            </CardContent>
          </Card>
          <Card>
            <CardHeader><CardTitle>SASRA / IFRS 9</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <Toggle label="SASRA Reports Enabled" description="Generate SASRA-compliant classification reports" checked={getBool('reports.sasra_enabled')} onChange={v => setBool('reports.sasra_enabled', v)}/>
              <Toggle label="Auto-Classify Loans (SASRA)" description="Automatically classify loans daily based on DPD" checked={getBool('sasra.auto_classify')} onChange={v => setBool('sasra.auto_classify', v)}/>
              <Toggle label="Auto-Provision (IFRS 9)" description="Run IFRS 9 ECL provisioning monthly" checked={getBool('ifrs9.auto_provision')} onChange={v => setBool('ifrs9.auto_provision', v)}/>
            </CardContent>
          </Card>
        </div>
      )}

      {tab === 'notifications' && (
        <Card>
          <CardHeader><CardTitle>Notification Channels</CardTitle></CardHeader>
          <CardContent className="space-y-4">
            <Toggle label="SMS Notifications" description="Send SMS notifications via Africa's Talking" checked={getBool('notifications.sms')} onChange={v => setBool('notifications.sms', v)}/>
            <Toggle label="Email Notifications" description="Send email notifications via SMTP" checked={getBool('notifications.email')} onChange={v => setBool('notifications.email', v)}/>
            <Toggle label="In-App Notifications" description="Show notifications inside the system" checked={getBool('notifications.in_app') || true} onChange={v => setBool('notifications.in_app', v)}/>
            <SectionDivider label="Notification Events"/>
            <Toggle label="Loan Disbursement Alert" description="Notify member when loan is disbursed" checked={getBool('notify.loan_disbursed')} onChange={v => setBool('notify.loan_disbursed', v)}/>
            <Toggle label="Repayment Reminder" description="Remind member 3 days before due date" checked={getBool('notify.repayment_reminder')} onChange={v => setBool('notify.repayment_reminder', v)}/>
            <Toggle label="Overdue Alert" description="Notify officer when loan goes overdue" checked={getBool('notify.overdue_alert')} onChange={v => setBool('notify.overdue_alert', v)}/>
            <Toggle label="Savings Interest Posted" description="Notify member when interest is credited" checked={getBool('notify.interest_posted')} onChange={v => setBool('notify.interest_posted', v)}/>
          </CardContent>
        </Card>
      )}

      {tab === 'features' && (
        <div className="space-y-4">
          <Card>
            <CardHeader><CardTitle>Module Features</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <Toggle label="Savings Module" description="Enable FOSA/BOSA savings accounts" checked={getBool('savings.interest_enabled') !== false} onChange={v => setBool('savings.interest_enabled', v)}/>
              <Toggle label="Shares Module" description="Enable member share accounts" checked={getBool('shares.enabled')} onChange={v => setBool('shares.enabled', v)}/>
              <Toggle label="Fixed Deposits" description="Enable fixed deposit accounts" checked={getBool('fd.enabled')} onChange={v => setBool('fd.enabled', v)}/>
              <Toggle label="Collections Module" description="Enable debt collections tracking" checked={getBool('collections.enabled')} onChange={v => setBool('collections.enabled', v)}/>
              <Toggle label="Payroll Module" description="Enable staff payroll processing" checked={getBool('payroll.enabled')} onChange={v => setBool('payroll.enabled', v)}/>
              <Toggle label="Fixed Assets Module" description="Enable fixed asset management" checked={getBool('assets.enabled')} onChange={v => setBool('assets.enabled', v)}/>
              <Toggle label="AML / Compliance" description="Enable Anti-Money Laundering checks" checked={getBool('aml.enabled')} onChange={v => setBool('aml.enabled', v)}/>
              <Toggle label="Group Lending" description="Enable group/chama loan products" checked={getBool('groups.enabled')} onChange={v => setBool('groups.enabled', v)}/>
            </CardContent>
          </Card>
        </div>
      )}

      {tab === 'financial' && (
        <Card>
          <CardHeader><CardTitle>Financial Year & System</CardTitle></CardHeader>
          <CardContent className="space-y-4">
            <div>
              <label className="block text-sm font-medium mb-1.5">Financial Year Start</label>
              <Input value={getVal('financial_year_start') || '01-01'} onChange={e => setVal('financial_year_start', e.target.value)} hint="Format: MM-DD (e.g. 01-01 for January 1)"/>
            </div>
            <div>
              <label className="block text-sm font-medium mb-1.5">Financial Year End</label>
              <Input value={getVal('financial_year_end') || '12-31'} onChange={e => setVal('financial_year_end', e.target.value)} hint="Format: MM-DD (e.g. 12-31 for December 31)"/>
            </div>
            <div>
              <label className="block text-sm font-medium mb-1.5">Base Currency</label>
              <Input value={getVal('system.currency') || 'KES'} onChange={e => setVal('system.currency', e.target.value)} hint="ISO 4217 currency code (e.g. KES, USD, UGX)"/>
            </div>
            <div>
              <label className="block text-sm font-medium mb-1.5">System Timezone</label>
              <Input value={getVal('system.timezone') || 'Africa/Nairobi'} onChange={e => setVal('system.timezone', e.target.value)} hint="IANA timezone (e.g. Africa/Nairobi)"/>
            </div>
          </CardContent>
        </Card>
      )}

      {tab === 'currencies' && (
        <div className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2"><Globe className="w-4 h-4"/> Active Currencies</CardTitle>
            </CardHeader>
            <CardContent>
              {!currencies || currencies.length === 0 ? (
                <p className="text-sm text-muted-foreground py-4 text-center">No foreign currencies configured. Only KES (base currency) is active.</p>
              ) : (
                <div className="space-y-2">
                  {currencies.map((c: any) => (
                    <div key={c.id} className="flex items-center justify-between p-3 border rounded-lg">
                      <div>
                        <span className="font-semibold">{c.code}</span>
                        <span className="text-muted-foreground ml-2">{c.name}</span>
                        {c.isBase && <span className="ml-2 text-xs bg-primary/10 text-primary px-2 py-0.5 rounded">Base</span>}
                      </div>
                      <div className="text-sm">1 {c.code} = {Number(c.rateToBase).toFixed(4)} KES</div>
                    </div>
                  ))}
                </div>
              )}
              <div className="mt-4 border-t pt-4">
                <p className="text-sm font-medium mb-3">Add / Update Currency</p>
                <AddCurrencyForm onSubmit={(d) => currencyMutation.mutate(d)} loading={currencyMutation.isPending}/>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {tab === 'holidays' && (
        <div className="space-y-4">
          <Card>
            <CardHeader><CardTitle className="flex items-center gap-2"><Calendar className="w-4 h-4"/> Holiday Calendar</CardTitle></CardHeader>
            <CardContent>
              {!holidays || holidays.length === 0 ? (
                <p className="text-sm text-muted-foreground py-4 text-center">No holidays configured.</p>
              ) : (
                <div className="space-y-2">
                  {holidays.map((h: any) => (
                    <div key={h.id} className="flex items-center justify-between p-3 border rounded-lg">
                      <div>
                        <span className="font-medium">{h.name}</span>
                        {h.isNational && <span className="ml-2 text-xs bg-blue-100 text-blue-700 px-2 py-0.5 rounded">National</span>}
                      </div>
                      <span className="text-sm text-muted-foreground">{new Date(h.date).toLocaleDateString('en-KE', { day:'numeric', month:'short', year:'numeric' })}</span>
                    </div>
                  ))}
                </div>
              )}
              <div className="mt-4 border-t pt-4">
                <p className="text-sm font-medium mb-3">Add Holiday</p>
                <AddHolidayForm onSubmit={(d) => holidayMutation.mutate(d)} loading={holidayMutation.isPending}/>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {tab === 'user-groups' && <UserGroupsTab />}
      {tab === 'access-control' && <AccessControlTab />}
      {tab === 'approval-routing' && <ApprovalRoutingTab />}
      {tab === 'company-profile' && <CompanyProfileTab />}
      {tab === 'branches' && <BranchesTab />}
    </div>
  )
}

function UserGroupsTab() {
  const qc = useQueryClient()
  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [selectedGroup, setSelectedGroup] = useState<any>(null)
  const [addUserId, setAddUserId] = useState('')

  const { data, isLoading } = useQuery({
    queryKey: ['user-groups'],
    queryFn: () => axios.get('/api/configuration/groups').then(r => r.data),
  })

  const { data: roles } = useQuery({
    queryKey: ['roles-list'],
    queryFn: () => axios.get('/api/admin/users?sub=roles').then(r => r.data.data ?? []),
  })

  const { data: users } = useQuery({
    queryKey: ['users-list'],
    queryFn: () => axios.get('/api/admin/users?pageSize=200').then(r => r.data.data ?? []),
  })

  const createMutation = useMutation({
    mutationFn: (d: any) => axios.post('/api/configuration/groups', d),
    onSuccess: () => { toast.success('Group created'); setName(''); setDescription(''); qc.invalidateQueries({ queryKey: ['user-groups'] }) },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed'),
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => axios.post('/api/configuration/groups', { action: 'delete', id }),
    onSuccess: () => { toast.success('Group deleted'); setSelectedGroup(null); qc.invalidateQueries({ queryKey: ['user-groups'] }) },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed'),
  })

  const addMemberMutation = useMutation({
    mutationFn: (d: any) => axios.post('/api/configuration/groups', { action: 'add-member', ...d }),
    onSuccess: () => { toast.success('Member added'); setAddUserId(''); qc.invalidateQueries({ queryKey: ['user-groups'] }) },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed'),
  })

  const removeMemberMutation = useMutation({
    mutationFn: (d: any) => axios.post('/api/configuration/groups', { action: 'remove-member', ...d }),
    onSuccess: () => { toast.success('Member removed'); qc.invalidateQueries({ queryKey: ['user-groups'] }) },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed'),
  })

  const groups = data?.data ?? []
  const selectedGroupData = selectedGroup ?? groups[0] ?? null

  return (
    <div className="space-y-6">
      <Alert variant="info">
        <div className="text-sm">
          <strong>Roles</strong> define <em>who a user is</em> (e.g. Loan Officer, Branch Manager) and come with pre-set permissions.
          <strong> Groups</strong> are collections of users you create for fine-grained access control — grant a group access to a module,
          and all members inherit those permissions. Both work together in the <strong>Access Control</strong> tab.
        </div>
      </Alert>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2"><UserCog className="w-4 h-4"/> Roles (Position / Job Function)</CardTitle>
          <p className="text-sm text-muted-foreground">Roles define what a user <em>is</em>. Assigned in User Management. Read-only here.</p>
        </CardHeader>
        <CardContent>
          {!roles ? <p className="text-sm text-muted-foreground">Loading...</p> : roles.length === 0 ? (
            <p className="text-sm text-muted-foreground py-2">No roles configured.</p>
          ) : (
            <div className="flex flex-wrap gap-2">
              {roles.map((r: any) => (
                <span key={r.id} className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-muted rounded-full text-sm">
                  <UserCog className="w-3.5 h-3.5 text-muted-foreground"/>
                  {r.name}
                  <span className="text-xs text-muted-foreground">({r._count?.userRoles ?? 0} users)</span>
                </span>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <Card className="lg:col-span-1">
          <CardHeader><CardTitle className="flex items-center gap-2"><Users className="w-4 h-4"/> Groups</CardTitle></CardHeader>
          <CardContent className="space-y-3">
            <div className="flex gap-2">
              <Input placeholder="Group name" value={name} onChange={e => setName(e.target.value)} />
              <Button size="sm" onClick={() => createMutation.mutate({ name, description })} loading={createMutation.isPending} disabled={!name}>
                <Plus className="w-4 h-4"/>
              </Button>
            </div>
            {isLoading ? <p className="text-sm text-muted-foreground">Loading...</p> : (
              <div className="space-y-1 max-h-96 overflow-y-auto">
                {groups.map((g: any) => (
                  <div key={g.id}
                    className={`flex items-center justify-between p-2 rounded cursor-pointer text-sm hover:bg-accent ${selectedGroupData?.id === g.id ? 'bg-accent font-medium' : ''}`}
                    onClick={() => setSelectedGroup(g)}>
                    <span>{g.name} <span className="text-muted-foreground">({g._count?.members ?? 0})</span></span>
                    <button onClick={(e) => { e.stopPropagation(); if (confirm('Delete this group?')) deleteMutation.mutate(g.id) }}>
                      <Trash2 className="w-3.5 h-3.5 text-destructive"/>
                    </button>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        {selectedGroupData && (
          <Card className="lg:col-span-2">
            <CardHeader><CardTitle>Group: {selectedGroupData.name}</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <div className="flex gap-2 items-end">
                <div className="flex-1">
                    <Select
                      label="Add User"
                      value={addUserId}
                      onChange={e => setAddUserId(e.target.value)}
                    options={(users ?? []).map((u: any) => ({ value: u.id, label: `${u.fullName ?? u.email} (${u.role ?? '—'})` }))}
                    placeholder="Select user..."
                  />
                </div>
                <Button size="sm" onClick={() => addMemberMutation.mutate({ groupId: selectedGroupData.id, userId: addUserId })} loading={addMemberMutation.isPending} disabled={!addUserId}>
                  <UserPlus className="w-4 h-4"/>
                </Button>
              </div>
              <SectionDivider label="Members" />
              <MemberList groupId={selectedGroupData.id} onRemove={(userId) => removeMemberMutation.mutate({ groupId: selectedGroupData.id, userId })} />
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  )
}

function MemberList({ groupId, onRemove }: { groupId: string; onRemove: (userId: string) => void }) {
  const { data, isLoading } = useQuery({
    queryKey: ['group-members', groupId],
    queryFn: () => axios.get(`/api/configuration/groups?groupId=${groupId}`).then(r => r.data.data ?? []),
    enabled: !!groupId,
  })
  const members = data ?? []

  if (isLoading) return <p className="text-sm text-muted-foreground">Loading members...</p>
  if (members.length === 0) return <p className="text-sm text-muted-foreground py-4 text-center">No members in this group.</p>
  return (
    <div className="space-y-2">
      {members.map((m: any) => (
        <div key={m.id} className="flex items-center justify-between p-2 border rounded text-sm">
          <span>{m.user?.fullName ?? m.user?.email ?? m.userId}</span>
          <button onClick={() => onRemove(m.userId)}><UserMinus className="w-3.5 h-3.5 text-muted-foreground hover:text-destructive"/></button>
        </div>
      ))}
    </div>
  )
}

const MODULE_PERMISSIONS: Record<string, { label: string; permissions: string[] }> = {
  loans:          { label: 'Loans',          permissions: ['view', 'create', 'edit', 'delete', 'approve', 'view_all', 'approve_all', 'disburse', 'write_off'] },
  members:        { label: 'Members',        permissions: ['view', 'create', 'edit', 'delete', 'view_all', 'blacklist', 'import', 'export'] },
  savings:        { label: 'Savings',        permissions: ['view', 'create', 'edit', 'delete', 'view_all', 'post_interest', 'reverse_transaction', 'waive_fees'] },
  shares:         { label: 'Shares',         permissions: ['view', 'create', 'edit', 'delete', 'approve', 'post_dividend'] },
  accounting:     { label: 'Accounting',     permissions: ['view', 'create', 'edit', 'delete', 'post_journal', 'approve_journal', 'view_all', 'close_period', 'reconcile'] },
  reports:        { label: 'Reports',        permissions: ['view', 'create', 'edit', 'delete', 'export', 'schedule'] },
  configuration:  { label: 'Configuration',  permissions: ['view', 'edit', 'delete'] },
  users:          { label: 'Users',          permissions: ['view', 'create', 'edit', 'delete', 'manage_roles', 'view_all'] },
  payroll:        { label: 'Payroll',        permissions: ['view', 'create', 'edit', 'delete', 'process', 'approve', 'view_all'] },
  collections:    { label: 'Collections',    permissions: ['view', 'create', 'edit', 'delete', 'assign', 'view_all'] },
  assets:         { label: 'Fixed Assets',   permissions: ['view', 'create', 'edit', 'delete', 'depreciate', 'dispose'] },
  expenses:       { label: 'Expenses',       permissions: ['view', 'create', 'edit', 'delete', 'approve', 'view_all'] },
  dashboard:      { label: 'Dashboard',      permissions: ['view'] },
  groups:         { label: 'Groups (Lending)', permissions: ['view', 'create', 'edit', 'delete', 'approve', 'view_all'] },
}

function AccessControlTab() {
  const qc = useQueryClient()
  const [module, setModule] = useState('loans')
  const [grantType, setGrantType] = useState<'USER' | 'GROUP'>('USER')
  const [grantToId, setGrantToId] = useState('')
  const [selectedPerms, setSelectedPerms] = useState<Record<string, boolean>>({})

  const { data, isLoading } = useQuery({
    queryKey: ['access-control', module],
    queryFn: () => axios.get(`/api/configuration/access?module=${module}`).then(r => r.data.data),
  })

  const { data: users } = useQuery({
    queryKey: ['users-list'],
    queryFn: () => axios.get('/api/admin/users?pageSize=200').then(r => r.data.data ?? []),
  })

  const { data: groups } = useQuery({
    queryKey: ['user-groups'],
    queryFn: () => axios.get('/api/configuration/groups').then(r => r.data.data ?? []),
  })

  const saveMutation = useMutation({
    mutationFn: (d: any) => axios.post('/api/configuration/access', d),
    onSuccess: () => { toast.success('Permissions saved'); setGrantToId(''); setSelectedPerms({}); qc.invalidateQueries({ queryKey: ['access-control'] }) },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed'),
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => axios.post('/api/configuration/access', { action: 'delete', id }),
    onSuccess: () => { toast.success('Permission removed'); qc.invalidateQueries({ queryKey: ['access-control'] }) },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed'),
  })

  function handleBulkSave() {
    const perms = Object.entries(selectedPerms).filter(([, v]) => v).map(([perm]) => ({ permission: perm, isAllowed: true }))
    if (!perms.length || !grantToId) return
    saveMutation.mutate({ action: 'bulk', module, grantType, grantToId, permissions: perms })
  }

  function togglePerm(perm: string) {
    setSelectedPerms(prev => ({ ...prev, [perm]: !prev[perm] }))
  }

  function handleModuleChange(m: string) {
    setModule(m)
    setSelectedPerms({})
  }

  const currentPerms = MODULE_PERMISSIONS[module] ?? MODULE_PERMISSIONS.loans
  const selectedCount = Object.values(selectedPerms).filter(Boolean).length
  const modules = Object.entries(MODULE_PERMISSIONS).map(([k, v]) => ({ value: k, label: v.label }))

  // Build existing permissions set for the selected grant target
  const existingPerms = data?.filter((ac: any) => ac.grantToId === grantToId) ?? []

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2"><Shield className="w-4 h-4"/> Grant Permissions</CardTitle>
          <p className="text-sm text-muted-foreground">Select a module, choose a user or group, then tick the permissions to grant. Save once to apply all.</p>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
            <Select label="Module" value={module} onChange={e => handleModuleChange(e.target.value)} options={modules} />
            <Select label="Grant To" value={grantType} onChange={e => { setGrantType(e.target.value as any); setSelectedPerms({}) }} options={[{ value: 'USER', label: 'User' }, { value: 'GROUP', label: 'User Group' }]} />
            <Select label="Target" value={grantToId} onChange={e => { setGrantToId(e.target.value); setSelectedPerms({}) }}
              options={(grantType === 'USER' ? (users ?? []) : (groups ?? [])).map((t: any) => ({
                value: t.id, label: t.fullName ?? t.name ?? t.email ?? t.id,
              }))}
              placeholder={`Select ${grantType.toLowerCase()}...`} />
          </div>

          <div>
            <p className="text-sm font-medium mb-3">Permissions for <strong>{currentPerms.label}</strong></p>
            <div className="flex flex-wrap gap-3">
              {currentPerms.permissions.map(perm => {
                const existing = existingPerms.find((ac: any) => ac.permission === perm)
                const alreadySet = existing && selectedPerms[perm] === undefined
                const checked = selectedPerms[perm] ?? alreadySet ? existing.isAllowed : false
                return (
                  <label key={perm} className={`flex items-center gap-2 px-3 py-2 border rounded-md cursor-pointer text-sm transition-colors ${checked ? 'border-primary bg-primary/5' : 'hover:bg-accent'}`}>
                    <input type="checkbox" checked={checked} onChange={() => togglePerm(perm)} className="rounded" />
                    <span className="font-medium">{perm.replace(/_/g, ' ')}</span>
                    {alreadySet && <span className="text-xs text-muted-foreground">({existing.isAllowed ? 'allowed' : 'denied'})</span>}
                  </label>
                )
              })}
            </div>
          </div>

          <div className="flex items-center gap-3 mt-6">
            <Button icon={<Save className="w-4 h-4"/>} loading={saveMutation.isPending}
              onClick={handleBulkSave} disabled={!selectedCount || !grantToId}>
              Save {selectedCount} Permission{selectedCount > 1 ? 's' : ''}
            </Button>
            {selectedCount > 0 && grantToId && (
              <p className="text-xs text-muted-foreground">Granting {selectedCount} permission(s) for <strong>{currentPerms.label}</strong> to selected {grantType.toLowerCase()}</p>
            )}
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader><CardTitle>Current Permissions — {currentPerms.label}</CardTitle></CardHeader>
        <CardContent>
          {isLoading ? <p className="text-sm text-muted-foreground">Loading...</p> : (
            <div className="space-y-2">
              {(!data || data.length === 0) ? (
                <p className="text-sm text-muted-foreground py-4 text-center">No access rules for this module.</p>
              ) : (
                <div className="overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="border-b text-left text-muted-foreground">
                        <th className="pb-2 font-medium">Permission</th>
                        <th className="pb-2 font-medium">Type</th>
                        <th className="pb-2 font-medium">Target</th>
                        <th className="pb-2 font-medium">Status</th>
                        <th className="pb-2"></th>
                      </tr>
                    </thead>
                    <tbody>
                      {data.map((ac: any) => (
                        <tr key={ac.id} className="border-b last:border-0">
                          <td className="py-2.5"><span className="font-mono text-xs bg-muted px-2 py-0.5 rounded">{ac.permission}</span></td>
                          <td className="py-2.5 text-muted-foreground">{ac.grantType === 'USER' ? 'User' : 'Group'}</td>
                          <td className="py-2.5 font-medium">{ac.grantToName ?? ac.grantToId?.slice(0, 8)}</td>
                          <td className="py-2.5">
                            <span className={`px-2 py-0.5 rounded text-xs font-medium ${ac.isAllowed ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                              {ac.isAllowed ? 'ALLOW' : 'DENY'}
                            </span>
                          </td>
                          <td className="py-2.5">
                            <button onClick={() => deleteMutation.mutate(ac.id)} className="text-muted-foreground hover:text-destructive">
                              <Trash2 className="w-3.5 h-3.5"/>
                            </button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}

function ApprovalRoutingTab() {
  const qc = useQueryClient()
  const [productId, setProductId] = useState('')
  const [approvalLevel, setApprovalLevel] = useState(1)
  const [assignmentType, setAssignmentType] = useState<'AUTO' | 'ROLE' | 'GROUP' | 'USER'>('AUTO')
  const [assignToRoleId, setAssignToRoleId] = useState('')
  const [assignToGroupId, setAssignToGroupId] = useState('')
  const [assignToUserId, setAssignToUserId] = useState('')

  const { data, isLoading } = useQuery({
    queryKey: ['approval-routing', productId],
    queryFn: () => axios.get(`/api/configuration/approval-routing${productId ? `?productId=${productId}` : ''}`).then(r => r.data.data),
  })

  const { data: products } = useQuery({
    queryKey: ['loan-products-mini'],
    queryFn: () => axios.get('/api/loans/products?pageSize=100').then(r => r.data.data ?? []),
  })

  const { data: roles } = useQuery({
    queryKey: ['roles-list'],
    queryFn: () => axios.get('/api/admin/users?sub=roles').then(r => r.data.data ?? []),
  })

  const { data: groups } = useQuery({
    queryKey: ['user-groups'],
    queryFn: () => axios.get('/api/configuration/groups').then(r => r.data.data ?? []),
  })

  const { data: users } = useQuery({
    queryKey: ['users-list'],
    queryFn: () => axios.get('/api/admin/users?pageSize=200').then(r => r.data.data ?? []),
  })

  const saveMutation = useMutation({
    mutationFn: (d: any) => axios.post('/api/configuration/approval-routing', d),
    onSuccess: () => { toast.success('Routing rule saved'); qc.invalidateQueries({ queryKey: ['approval-routing'] }) },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed'),
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => axios.post('/api/configuration/approval-routing', { action: 'delete', id }),
    onSuccess: () => { toast.success('Rule deleted'); qc.invalidateQueries({ queryKey: ['approval-routing'] }) },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed'),
  })

  const assignmentOptions: { value: string; label: string }[] = [
    { value: 'AUTO', label: 'Auto (least workload)' },
    { value: 'ROLE', label: 'Role-based' },
    { value: 'GROUP', label: 'User Group' },
    { value: 'USER', label: 'Specific User' },
  ]

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader><CardTitle className="flex items-center gap-2"><Route className="w-4 h-4"/> Add Routing Rule</CardTitle></CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <Select label="Loan Product" value={productId} onChange={e => setProductId(e.target.value)}
              options={[{ value: '', label: 'All Products (Global)' }, ...(products ?? []).map((p: any) => ({ value: p.id, label: p.name }))]} />
            <div>
              <label className="block text-sm font-medium mb-1.5">Approval Level</label>
              <input type="number" min={1} max={10} value={approvalLevel}
                onChange={e => setApprovalLevel(parseInt(e.target.value) || 1)}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm" />
            </div>
            <Select label="Assignment Type" value={assignmentType} onChange={e => setAssignmentType(e.target.value as any)} options={assignmentOptions} />
            {assignmentType === 'ROLE' && (
              <Select label="Role" value={assignToRoleId} onChange={e => setAssignToRoleId(e.target.value)}
                options={(roles ?? []).map((r: any) => ({ value: r.id, label: r.name ?? r.id }))} placeholder="Select role..." />
            )}
            {assignmentType === 'GROUP' && (
              <Select label="User Group" value={assignToGroupId} onChange={e => setAssignToGroupId(e.target.value)}
                options={(groups ?? []).map((g: any) => ({ value: g.id, label: g.name }))} placeholder="Select group..." />
            )}
            {assignmentType === 'USER' && (
              <Select label="User" value={assignToUserId} onChange={e => setAssignToUserId(e.target.value)}
                options={(users ?? []).map((u: any) => ({ value: u.id, label: u.fullName ?? u.email }))} placeholder="Select user..." />
            )}
          </div>
          <div className="mt-4">
            <Button onClick={() => saveMutation.mutate({
              productId: productId || null,
              approvalLevel,
              assignmentType,
              assignToRoleId: assignmentType === 'ROLE' ? assignToRoleId : null,
              assignToGroupId: assignmentType === 'GROUP' ? assignToGroupId : null,
              assignToUserId: assignmentType === 'USER' ? assignToUserId : null,
            })} loading={saveMutation.isPending} icon={<Plus className="w-4 h-4"/>}>
              Add Rule
            </Button>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader><CardTitle>Current Routing Rules</CardTitle></CardHeader>
        <CardContent>
          {isLoading ? <p className="text-sm text-muted-foreground">Loading...</p> : (
            <div className="space-y-2">
              {(!data || data.length === 0) ? (
                <p className="text-sm text-muted-foreground py-4 text-center">No routing rules configured. Approval levels will remain unassigned.</p>
              ) : (
                data.map((rule: any) => (
                  <div key={rule.id} className="flex items-center justify-between p-3 border rounded text-sm">
                    <div className="flex items-center gap-3">
                      <span className="font-mono text-xs bg-muted px-2 py-0.5 rounded">L{rule.approvalLevel}</span>
                      <span className="text-muted-foreground">{rule.productId ? 'Product-specific' : 'Global'}</span>
                      <span className="font-medium">{rule.assignmentType}</span>
                      {rule.assignToUserId && <span>→ User: {rule.assignToUserId.slice(0, 8)}...</span>}
                      {rule.assignToGroupId && <span>→ Group: {rule.assignToGroupId.slice(0, 8)}...</span>}
                      {rule.assignToRoleId && <span>→ Role: {rule.assignToRoleId.slice(0, 8)}...</span>}
                    </div>
                    <button onClick={() => deleteMutation.mutate(rule.id)}><Trash2 className="w-3.5 h-3.5 text-destructive"/></button>
                  </div>
                ))
              )}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}

function AddCurrencyForm({ onSubmit, loading }: { onSubmit: (d: any) => void, loading: boolean }) {
  const [form, setForm] = useState({ code: '', name: '', symbol: '', rateToBase: '' })
  function handle() {
    if (!form.code || !form.name || !form.symbol || !form.rateToBase) return
    onSubmit({ ...form, rateToBase: parseFloat(form.rateToBase) })
    setForm({ code: '', name: '', symbol: '', rateToBase: '' })
  }
  return (
    <div className="grid grid-cols-2 gap-3">
      <Input label="Code" placeholder="USD" value={form.code} onChange={e => setForm(p => ({...p, code: e.target.value.toUpperCase()}))} maxLength={3}/>
      <Input label="Name" placeholder="US Dollar" value={form.name} onChange={e => setForm(p => ({...p, name: e.target.value}))}/>
      <Input label="Symbol" placeholder="$" value={form.symbol} onChange={e => setForm(p => ({...p, symbol: e.target.value}))}/>
      <Input label="Rate to KES" type="number" placeholder="130.50" value={form.rateToBase} onChange={e => setForm(p => ({...p, rateToBase: e.target.value}))}/>
      <div className="col-span-2"><Button onClick={handle} loading={loading} icon={<Plus className="w-4 h-4"/>}>Add Currency</Button></div>
    </div>
  )
}

function AddHolidayForm({ onSubmit, loading }: { onSubmit: (d: any) => void, loading: boolean }) {
  const [form, setForm] = useState({ date: '', name: '', isNational: true, isRecurring: true })
  function handle() {
    if (!form.date || !form.name) return
    onSubmit(form)
    setForm({ date: '', name: '', isNational: true, isRecurring: true })
  }
  return (
    <div className="grid grid-cols-2 gap-3">
      <Input label="Date" type="date" value={form.date} onChange={e => setForm(p => ({...p, date: e.target.value}))}/>
      <Input label="Holiday Name" placeholder="Mashujaa Day" value={form.name} onChange={e => setForm(p => ({...p, name: e.target.value}))}/>
      <Toggle label="National Holiday" checked={form.isNational} onChange={v => setForm(p => ({...p, isNational: v}))}/>
      <Toggle label="Recurring Annually" checked={form.isRecurring} onChange={v => setForm(p => ({...p, isRecurring: v}))}/>
      <div className="col-span-2"><Button onClick={handle} loading={loading} icon={<Plus className="w-4 h-4"/>}>Add Holiday</Button></div>
    </div>
  )
}

function CompanyProfileTab() {
  const qc = useQueryClient()
  const [form, setForm] = useState<any>(null)
  const [dirty, setDirty] = useState(false)
  const [uploading, setUploading] = useState(false)
  const [logoPreview, setLogoPreview] = useState<string | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)

  const { data, isLoading, error: fetchError } = useQuery({
    queryKey: ['organisation'],
    queryFn: () => axios.get('/api/organisation').then(r => r.data.data),
  })

  const saveMutation = useMutation({
    mutationFn: (payload: any) => axios.patch('/api/organisation', payload),
    onSuccess: () => {
      toast.success('Company profile saved')
      qc.invalidateQueries({ queryKey: ['organisation'] })
      setDirty(false)
    },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed to save'),
  })

  useEffect(() => {
    if (data && !dirty) setForm({ ...data })
  }, [data])

  function set(field: string, value: string) {
    setForm((prev: any) => ({ ...prev, [field]: value }))
    setDirty(true)
  }

  async function handleLogoUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0]
    if (!file) return

    if (!['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(file.type)) {
      toast.error('Only JPEG, PNG, GIF, and WebP images are allowed')
      return
    }
    if (file.size > 2 * 1024 * 1024) {
      toast.error('File size must be under 2 MB')
      return
    }

    setUploading(true)
    try {
      const fd = new FormData()
      fd.append('file', file)
      const res = await axios.post('/api/upload', fd)
      const url = res.data.data.url
      set('logoUrl', url)
      setLogoPreview(null)
      toast.success('Logo uploaded')
    } catch (e: any) {
      toast.error(e.response?.data?.error ?? 'Failed to upload logo')
    } finally {
      setUploading(false)
    }
  }

  if (isLoading) return <div className="p-6 text-muted-foreground">Loading company profile...</div>
  if (fetchError) return <Alert variant="error">Failed to load company profile. Make sure you have configuration.view permission.</Alert>
  if (!form) return null

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2"><Building2 className="w-4 h-4"/> Company Information</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <Input label="Organisation Name" value={form.name} disabled hint="Cannot be changed" />
            <Input label="Legal Name" value={form.legalName ?? ''} onChange={e => set('legalName', e.target.value)} />
            <Input label="Registration No." value={form.registrationNo ?? ''} onChange={e => set('registrationNo', e.target.value)} />
            <Input label="Tax PIN" value={form.taxPin ?? ''} onChange={e => set('taxPin', e.target.value)} />
            <Input label="Regulator No." value={form.regulatorNo ?? ''} onChange={e => set('regulatorNo', e.target.value)} />
            <Input label="Regulator Type" value={form.regulatorType ?? ''} onChange={e => set('regulatorType', e.target.value)} placeholder="e.g. SASRA" />
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader><CardTitle>Address & Contact</CardTitle></CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <Input label="Physical Address" value={form.physicalAddress ?? ''} onChange={e => set('physicalAddress', e.target.value)} />
            <Input label="Postal Address" value={form.postalAddress ?? ''} onChange={e => set('postalAddress', e.target.value)} />
            <Input label="City" value={form.city ?? ''} onChange={e => set('city', e.target.value)} />
            <Input label="County" value={form.county ?? ''} onChange={e => set('county', e.target.value)} />
            <Input label="Country" value={form.country ?? ''} onChange={e => set('country', e.target.value)} />
            <Input label="Phone" value={form.phone ?? ''} onChange={e => set('phone', e.target.value)} />
            <Input label="Alternate Phone" value={form.phoneAlt ?? ''} onChange={e => set('phoneAlt', e.target.value)} />
            <Input label="Email" type="email" value={form.email ?? ''} onChange={e => set('email', e.target.value)} />
            <Input label="Website" value={form.website ?? ''} onChange={e => set('website', e.target.value)} />
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader><CardTitle>Organisation Logo</CardTitle></CardHeader>
        <CardContent>
          <div className="flex items-start gap-6">
            <div className="shrink-0">
              {logoPreview ? (
                <img src={logoPreview} alt="Preview" className="w-24 h-24 rounded-xl border object-contain bg-muted" />
              ) : form.logoUrl ? (
                <img src={form.logoUrl} alt="Current logo" className="w-24 h-24 rounded-xl border object-contain bg-muted" />
              ) : (
                <div className="w-24 h-24 rounded-xl border bg-muted flex items-center justify-center text-muted-foreground">
                  <Building2 className="w-8 h-8" />
                </div>
              )}
            </div>
            <div className="space-y-3">
              <p className="text-sm text-muted-foreground">Upload a logo for your organisation. Recommended size: 200x200px. Max 2 MB.</p>
              <div className="flex items-center gap-3">
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/jpeg,image/png,image/gif,image/webp"
                  onChange={handleLogoUpload}
                  className="hidden"
                />
                <Button type="button" variant="outline" size="sm" loading={uploading} onClick={() => fileInputRef.current?.click()}>
                  Choose File
                </Button>
                <span className="text-xs text-muted-foreground">or</span>
                <Input
                  placeholder="Paste image URL..."
                  value={form.logoUrl ?? ''}
                  onChange={e => { set('logoUrl', e.target.value); setLogoPreview(e.target.value) }}
                  className="max-w-xs text-sm"
                />
              </div>
              {form.logoUrl && (
                <Button type="button" variant="ghost" size="xs" onClick={() => { set('logoUrl', ''); setLogoPreview(null) }}>
                  <X className="w-3.5 h-3.5 mr-1" /> Remove Logo
                </Button>
              )}
            </div>
          </div>
        </CardContent>
      </Card>

      {dirty && (
        <div className="flex justify-end">
          <Button icon={<Save className="w-4 h-4"/>} loading={saveMutation.isPending}
            onClick={() => {
              const payload: Record<string, any> = {}
              const editable = ['legalName','registrationNo','taxPin','regulatorNo','regulatorType','physicalAddress','postalAddress','city','county','country','phone','phoneAlt','email','website','logoUrl']
              for (const k of editable) {
                if (form[k] !== undefined && form[k] !== null) payload[k] = form[k]
              }
              saveMutation.mutate(payload)
            }}>
            Save Changes
          </Button>
        </div>
      )}
    </div>
  )
}

function BranchesTab() {
  const qc = useQueryClient()
  const [showForm, setShowForm] = useState(false)
  const [editing, setEditing] = useState<any>(null)
  const [form, setForm] = useState({ name: '', code: '', address: '', city: '', county: '', phone: '', email: '', isHeadOffice: false })

  const { data, isLoading, error: fetchError, refetch: refetchBranches } = useQuery({
    queryKey: ['configuration-branches'],
    queryFn: () => axios.get('/api/branches').then(r => r.data.data),
    refetchOnMount: 'always',
  })

  const createMutation = useMutation({
    mutationFn: (d: any) => axios.post('/api/branches', d),
    onSuccess: () => { toast.success('Branch created'); resetForm(); refetchBranches() },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed to create branch'),
  })

  const updateMutation = useMutation({
    mutationFn: (d: any) => axios.patch(`/api/branches/${editing.id}`, d),
    onSuccess: () => { toast.success('Branch updated'); resetForm(); refetchBranches() },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed to update branch'),
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => axios.delete(`/api/branches/${id}`),
    onSuccess: () => { toast.success('Branch deleted'); refetchBranches() },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed to delete branch'),
  })

  function resetForm() {
    setShowForm(false)
    setEditing(null)
    setForm({ name: '', code: '', address: '', city: '', county: '', phone: '', email: '', isHeadOffice: false })
  }

  function startEdit(branch: any) {
    setEditing(branch)
    setForm({ name: branch.name, code: branch.code, address: branch.address ?? '', city: branch.city ?? '', county: branch.county ?? '', phone: branch.phone ?? '', email: branch.email ?? '', isHeadOffice: branch.isHeadOffice })
    setShowForm(true)
  }

  function handleSubmit() {
    if (!form.name || !form.code) return
    if (editing) {
      updateMutation.mutate(form)
    } else {
      createMutation.mutate(form)
    }
  }

  const branches = data ?? []

  return (
    <div className="space-y-4">
      {!showForm ? (
        <div className="flex justify-end">
          <Button icon={<Plus className="w-4 h-4"/>} onClick={() => setShowForm(true)}>Add Branch</Button>
        </div>
      ) : (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Building className="w-4 h-4"/>
              {editing ? 'Edit Branch' : 'New Branch'}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              <Input label="Branch Name" value={form.name} onChange={e => setForm(p => ({...p, name: e.target.value}))} placeholder="Nairobi Branch" />
              <Input label="Branch Code" value={form.code} onChange={e => setForm(p => ({...p, code: e.target.value.toUpperCase()}))} placeholder="NB001" maxLength={20} />
              <Input label="Address" value={form.address} onChange={e => setForm(p => ({...p, address: e.target.value}))} />
              <Input label="City" value={form.city} onChange={e => setForm(p => ({...p, city: e.target.value}))} />
              <Input label="County" value={form.county} onChange={e => setForm(p => ({...p, county: e.target.value}))} />
              <Input label="Phone" value={form.phone} onChange={e => setForm(p => ({...p, phone: e.target.value}))} />
              <Input label="Email" type="email" value={form.email} onChange={e => setForm(p => ({...p, email: e.target.value}))} />
              <div className="flex items-end pb-2">
                <Toggle label="Head Office" checked={form.isHeadOffice} onChange={v => setForm(p => ({...p, isHeadOffice: v}))} />
              </div>
            </div>
            <div className="flex gap-2 mt-4">
              <Button icon={<Save className="w-4 h-4"/>} loading={createMutation.isPending || updateMutation.isPending} onClick={handleSubmit} disabled={!form.name || !form.code}>
                {editing ? 'Update Branch' : 'Create Branch'}
              </Button>
              <Button variant="ghost" onClick={resetForm}>Cancel</Button>
            </div>
          </CardContent>
        </Card>
      )}

      <Card>
        <CardHeader><CardTitle className="flex items-center gap-2"><Building2 className="w-4 h-4"/> Branches</CardTitle></CardHeader>
        <CardContent>
          {fetchError ? <Alert variant="error">Failed to load branches. Verify the API is accessible.</Alert> :
           isLoading ? <p className="text-sm text-muted-foreground">Loading...</p> : branches.length === 0 ? (
            <p className="text-sm text-muted-foreground py-4 text-center">No branches configured.</p>
          ) : (
            <div className="space-y-2">
              {branches.map((b: any) => (
                <div key={b.id} className="flex items-center justify-between p-3 border rounded-lg">
                  <div className="flex items-center gap-3">
                    <div>
                      <span className="font-semibold">{b.name}</span>
                      <span className="text-muted-foreground ml-2 text-sm">({b.code})</span>
                      {b.isHeadOffice && <span className="ml-2 text-xs bg-primary/10 text-primary px-2 py-0.5 rounded">HQ</span>}
                      {!b.isActive && <span className="ml-2 text-xs bg-red-100 text-red-700 px-2 py-0.5 rounded">Inactive</span>}
                    </div>
                    <span className="text-xs text-muted-foreground">{b._count?.userAssignments ?? 0} user(s)</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <button onClick={() => startEdit(b)} className="text-muted-foreground hover:text-foreground">
                      <Settings className="w-3.5 h-3.5"/>
                    </button>
                    <button onClick={() => { if (confirm('Delete this branch?')) deleteMutation.mutate(b.id) }} className="text-muted-foreground hover:text-destructive">
                      <Trash2 className="w-3.5 h-3.5"/>
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
