'use client'

import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import axios from 'axios'
import { toast } from 'sonner'
import { Settings, Save } from 'lucide-react'
import { Button, Card, CardHeader, CardTitle, CardContent, Toggle, Input, Alert, Tabs, Badge, PageHeader, SectionDivider } 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 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 configs: Record<string, string> = {}
  data?.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:'ifrs9',         label:'IFRS 9 / SASRA' },
    { id:'notifications', label:'Notifications' },
    { id:'aml',           label:'AML' },
    { id:'features',      label:'Features' },
    { id:'financial',     label:'Financial Year' },
    { id:'currencies',    label:'Currencies' },
  ]

  return (
    <div className="p-6 space-y-5 max-w-screen-xl mx-auto">
      <PageHeader
        title="System Configuration"
        description="All toggleable settings that control system behaviour"
        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' && (
        <div className="space-y-5">
          <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. Drag to reorder (or type the order).</p>
                <Input value={getVal('payment_allocation_order')} 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)}/>
            </CardContent>
          </Card>
          <Card>
            <CardHeader><CardTitle>Cashbook Settings</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <Toggle label="Per-Branch Cashbook" description="Each branch maintains its own separate cashbook" checked={getBool('per_branch_cashbook')} onChange={v => setBool('per_branch_cashbook', v)}/>
              <div>
                <label className="block text-sm font-medium mb-1.5">Petty Cash Limit (KES)</label>
                <Input type="number" value={getVal('petty_cash_limit')} onChange={e => setVal('petty_cash_limit', e.target.value)}/>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {tab === 'loans' && (
        <div className="space-y-5">
          <Card>
            <CardHeader><CardTitle>Loan Application Rules</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <Toggle label="Block CRB-Listed Applicants" description="Members with CRB status of LISTED or BLACKLISTED cannot submit loan applications" checked={getBool('crb_block_on_application')} onChange={v => setBool('crb_block_on_application', v)}/>
              <div>
                <label className="block text-sm font-medium mb-1.5">Minimum KYC Score for Loan (%)</label>
                <Input type="number" min={0} max={100} value={getVal('kyc_min_score_for_loan')} onChange={e => setVal('kyc_min_score_for_loan', e.target.value)} hint="Members with KYC score below this cannot apply for loans (0 = disabled)"/>
              </div>
              <Toggle label="Enforce Guarantors" description="Enforce guarantor requirements as configured on loan products" checked={getBool('guarantor_enforcement')} onChange={v => setBool('guarantor_enforcement', v)}/>
              <Toggle label="Enforce Collateral" description="Enforce collateral requirements as configured on loan products" checked={getBool('collateral_enforcement')} onChange={v => setBool('collateral_enforcement', v)}/>
            </CardContent>
          </Card>
          <Card>
            <CardHeader><CardTitle>Approval Settings</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <Toggle label="Maker-Checker Enforcement" description="The user who initiates an action cannot approve their own action (NEVER turn this off in production)" checked={getBool('maker_checker_enforced')} onChange={v => setBool('maker_checker_enforced', v)}/>
              <div>
                <label className="block text-sm font-medium mb-1.5">Approval Escalation Hours</label>
                <Input type="number" value={getVal('approval_escalation_hours')} onChange={e => setVal('approval_escalation_hours', e.target.value)} hint="Hours before a pending approval is auto-escalated"/>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {tab === 'ifrs9' && (
        <div className="space-y-5">
          <Card>
            <CardHeader><CardTitle>IFRS 9 ECL Engine</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <Toggle label="Enable IFRS 9 ECL Engine" description="Compute Expected Credit Losses automatically on scheduled run dates" checked={getBool('ifrs9_enabled')} onChange={v => setBool('ifrs9_enabled', v)}/>
              <div>
                <label className="block text-sm font-medium mb-1.5">Monthly ECL Run Day</label>
                <Input type="number" min={1} max={28} value={getVal('ifrs9_run_day')} onChange={e => setVal('ifrs9_run_day', e.target.value)} hint="Day of the month to run IFRS 9 calculations (1–28)"/>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader><CardTitle>IFRS 9 Stage Thresholds</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <Alert variant="info">These thresholds determine when a loan moves to Stage 2 or Stage 3 based on Days Past Due (DPD).</Alert>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <Input label="Stage 2 Threshold (DPD)" type="number" value={getVal('stage2_dpd_threshold')} onChange={e => setVal('stage2_dpd_threshold', e.target.value)} hint="Default: 31 days"/>
                <Input label="Stage 3 Threshold (DPD)" type="number" value={getVal('stage3_dpd_threshold')} onChange={e => setVal('stage3_dpd_threshold', e.target.value)} hint="Default: 91 days"/>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader><CardTitle>SASRA Classification Thresholds</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <Input label="WATCH Threshold (DPD)" type="number" value={getVal('watch_dpd_threshold')} onChange={e => setVal('watch_dpd_threshold', e.target.value)} hint="Default: 1 day"/>
                <Input label="SUBSTANDARD Threshold (DPD)" type="number" value={getVal('substandard_dpd_threshold')} onChange={e => setVal('substandard_dpd_threshold', e.target.value)} hint="Default: 31 days"/>
                <Input label="DOUBTFUL Threshold (DPD)" type="number" value={getVal('doubtful_dpd_threshold')} onChange={e => setVal('doubtful_dpd_threshold', e.target.value)} hint="Default: 91 days"/>
                <Input label="LOSS Threshold (DPD)" type="number" value={getVal('loss_dpd_threshold')} onChange={e => setVal('loss_dpd_threshold', e.target.value)} hint="Default: 181 days"/>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader><CardTitle>Write-Off Settings</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <Toggle label="Recovery Tracking After Write-Off" description="Continue tracking recoveries for written-off loans" checked={getBool('recovery_tracking_enabled')} onChange={v => setBool('recovery_tracking_enabled', v)}/>
              <Toggle label="Include Written-Off Loans in PAR" description="Include written-off loan balances in PAR calculation (not recommended)" checked={getBool('writeoff_in_par')} onChange={v => setBool('writeoff_in_par', v)}/>
              <div>
                <label className="block text-sm font-medium mb-1.5">Write-Off Approval Levels</label>
                <Input type="number" min={1} max={3} value={getVal('writeoff_approval_levels')} onChange={e => setVal('writeoff_approval_levels', e.target.value)}/>
              </div>
            </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 to members and staff" checked={getBool('sms_enabled')} onChange={v => setBool('sms_enabled', v)}/>
            <Toggle label="Email Notifications" description="Send email notifications to members and staff" checked={getBool('email_enabled')} onChange={v => setBool('email_enabled', v)}/>
            <Toggle label="In-App Notifications" description="Show in-app notifications in the web interface" checked={getBool('in_app_enabled')} onChange={v => setBool('in_app_enabled', v)}/>
            <div>
              <label className="block text-sm font-medium mb-1.5">Repayment Reminder Days Before Due</label>
              <Input type="number" min={0} max={30} value={getVal('reminder_days_before')} onChange={e => setVal('reminder_days_before', e.target.value)} hint="Send reminder this many days before the due date (0 = disabled)"/>
            </div>
          </CardContent>
        </Card>
      )}

      {tab === 'aml' && (
        <Card>
          <CardHeader><CardTitle>AML & Compliance</CardTitle></CardHeader>
          <CardContent className="space-y-4">
            <Toggle label="PEP Screening at Onboarding" description="Screen new members against Politically Exposed Persons list" checked={getBool('pep_screening_enabled')} onChange={v => setBool('pep_screening_enabled', v)}/>
            <Toggle label="Sanctions Screening" description="Screen members against OFAC and other sanctions lists" checked={getBool('sanctions_screening_enabled')} onChange={v => setBool('sanctions_screening_enabled', v)}/>
            <div>
              <label className="block text-sm font-medium mb-1.5">AML Transaction Threshold (KES)</label>
              <Input type="number" value={getVal('aml_txn_threshold_kes')} onChange={e => setVal('aml_txn_threshold_kes', e.target.value)} hint="Transactions above this amount trigger an AML flag for review"/>
            </div>
          </CardContent>
        </Card>
      )}

      {tab === 'features' && (
        <Card>
          <CardHeader><CardTitle>Feature Toggles</CardTitle></CardHeader>
          <CardContent className="space-y-4">
            <Toggle label="Member Self-Service Portal" description="Allow members to log in and view their accounts, loans, and statements" checked={getBool('member_portal_enabled')} onChange={v => setBool('member_portal_enabled', v)}/>
            <Toggle label="Public Loan Application Form" description="Enable a public-facing loan application form (for marketing/lead generation)" checked={getBool('public_loan_form_enabled')} onChange={v => setBool('public_loan_form_enabled', v)}/>
            <Toggle label="Digital Signature on Agreements" description="Require e-signature on loan agreements before disbursement" checked={getBool('digital_signature_enabled')} onChange={v => setBool('digital_signature_enabled', v)}/>
            <Toggle label="FOSA Auto-Debit (Global Default)" description="Global default setting for FOSA auto-debit on new loans (overrideable per product)" checked={getBool('fosa_auto_debit_global')} onChange={v => setBool('fosa_auto_debit_global', v)}/>
          </CardContent>
        </Card>
      )}

      {tab === 'financial' && (
        <Card>
          <CardHeader><CardTitle>Financial Year</CardTitle></CardHeader>
          <CardContent className="space-y-4">
            <Alert variant="info">Changes to financial year dates take effect from the next run. Existing records are not retroactively adjusted.</Alert>
            <div className="grid grid-cols-2 gap-4">
              <Input label="Financial Year Start (DD-MM)" value={getVal('financial_year_start')} onChange={e => setVal('financial_year_start', e.target.value)} hint="e.g. 01-01 for January 1st"/>
              <Input label="Financial Year End (DD-MM)" value={getVal('financial_year_end')} onChange={e => setVal('financial_year_end', e.target.value)} hint="e.g. 12-31 for December 31st"/>
            </div>
          </CardContent>
        </Card>
      )}

      {tab === 'currencies' && (
        <Card>
          <CardHeader><CardTitle>Currencies & Exchange Rates</CardTitle><Button variant="outline" size="sm">+ Add Currency</Button></CardHeader>
          <CardContent>
            <p className="text-sm text-muted-foreground mb-4">Base currency is KES. Exchange rates are used for multi-currency reporting.</p>
            <div className="space-y-2">
              {[
                { code:'KES', name:'Kenyan Shilling', rate:'1.000000', isBase:true },
                { code:'USD', name:'US Dollar', rate:'129.40', isBase:false },
                { code:'EUR', name:'Euro', rate:'140.20', isBase:false },
                { code:'GBP', name:'British Pound', rate:'164.80', isBase:false },
                { code:'UGX', name:'Uganda Shilling', rate:'0.034', isBase:false },
              ].map(c => (
                <div key={c.code} className="flex items-center justify-between p-3 border rounded-lg">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-7 bg-muted rounded flex items-center justify-center text-xs font-bold">{c.code}</div>
                    <div>
                      <p className="text-sm font-medium">{c.name}</p>
                      {c.isBase && <Badge variant="info">Base Currency</Badge>}
                    </div>
                  </div>
                  {!c.isBase && (
                    <div className="flex items-center gap-2">
                      <span className="text-sm text-muted-foreground">1 {c.code} =</span>
                      <Input className="w-24 text-right" defaultValue={c.rate}/>
                      <span className="text-sm text-muted-foreground">KES</span>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
