'use client'

import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import axios from 'axios'
import { toast } from 'sonner'
import { Settings } from 'lucide-react'
import { Modal, Button, Input, Select, Toggle } from '@/components/ui/components'

interface FeeSettingsProps {
  accountType: 'FOSA' | 'BOSA'
}

export default function FeeSettings({ accountType }: FeeSettingsProps) {
  const qc = useQueryClient()
  const [open, setOpen] = useState(false)

  const { data } = useQuery({
    queryKey: ['savings-fees', accountType],
    queryFn: () => axios.get(`/api/savings/fees?accountType=${accountType}`).then(r => r.data.data ?? []),
    enabled: open,
  })

  const fees: Record<string, any> = {}
  for (const f of data ?? []) fees[f.transactionType] = f

  const [deposit, setDeposit] = useState<any>({ feeModel: 'FLAT', flatAmount: '', percentageRate: '', minFee: '', maxFee: '', glIncomeCode: '4003', isActive: true })
  const [withdrawal, setWithdrawal] = useState<any>({ feeModel: 'FLAT', flatAmount: '', percentageRate: '', minFee: '', maxFee: '', glIncomeCode: '4003', isActive: true })

  function openSettings() {
    const dep = fees['DEPOSIT'] || { feeModel: 'FLAT', flatAmount: '', percentageRate: '', minFee: '', maxFee: '', glIncomeCode: '4003', isActive: true }
    const wd = fees['WITHDRAWAL'] || { feeModel: 'FLAT', flatAmount: '', percentageRate: '', minFee: '', maxFee: '', glIncomeCode: '4003', isActive: true }
    setDeposit({ ...dep, flatAmount: String(dep.flatAmount ?? ''), percentageRate: String(dep.percentageRate ?? ''), minFee: String(dep.minFee ?? ''), maxFee: String(dep.maxFee ?? '') })
    setWithdrawal({ ...wd, flatAmount: String(wd.flatAmount ?? ''), percentageRate: String(wd.percentageRate ?? ''), minFee: String(wd.minFee ?? ''), maxFee: String(wd.maxFee ?? '') })
    setOpen(true)
  }

  const saveMutation = useMutation({
    mutationFn: (payload: any) => axios.post('/api/savings/fees', payload),
    onSuccess: () => { toast.success('Fee settings saved'); qc.invalidateQueries({ queryKey: ['savings-fees'] }) },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed to save'),
  })

  function save(transactionType: string, form: any) {
    const payload: any = { accountType, transactionType, feeModel: form.feeModel, glIncomeCode: form.glIncomeCode || '4003', isActive: form.isActive }
    if (form.feeModel === 'FLAT' || form.feeModel === 'BOTH') payload.flatAmount = parseFloat(form.flatAmount) || 0
    if (form.feeModel === 'PERCENTAGE' || form.feeModel === 'BOTH') payload.percentageRate = parseFloat(form.percentageRate) || 0
    if (form.minFee) payload.minFee = parseFloat(form.minFee)
    if (form.maxFee) payload.maxFee = parseFloat(form.maxFee)
    saveMutation.mutate(payload)
  }

  function FeeForm({ label, form, setForm, onSave }: { label: string; form: any; setForm: any; onSave: () => void }) {
    return (
      <div className="space-y-3 border rounded-lg p-4">
        <div className="flex items-center justify-between">
          <h4 className="font-medium text-sm">{label}</h4>
          <Toggle checked={form.isActive} onChange={v => setForm((f: any) => ({ ...f, isActive: v }))} label={form.isActive ? 'Enabled' : 'Disabled'}/>
        </div>
        <Select label="Fee Model" value={form.feeModel} onChange={e => setForm((f: any) => ({ ...f, feeModel: e.target.value }))}
          options={[{ value: 'FLAT', label: 'Flat Amount (KES)' }, { value: 'PERCENTAGE', label: 'Percentage (%)' }, { value: 'BOTH', label: 'Flat + Percentage' }]}/>
        {(form.feeModel === 'FLAT' || form.feeModel === 'BOTH') && (
          <Input label="Flat Amount (KES)" type="number" min={0} step="0.01" value={form.flatAmount}
            onChange={e => setForm((f: any) => ({ ...f, flatAmount: e.target.value }))} placeholder="50"/>
        )}
        {(form.feeModel === 'PERCENTAGE' || form.feeModel === 'BOTH') && (
          <Input label="Percentage Rate (%)" type="number" min={0} step="0.01" value={form.percentageRate}
            onChange={e => setForm((f: any) => ({ ...f, percentageRate: e.target.value }))} placeholder="0.5"/>
        )}
        <div className="grid grid-cols-2 gap-3">
          <Input label="Minimum Fee (KES)" type="number" min={0} step="0.01" value={form.minFee}
            onChange={e => setForm((f: any) => ({ ...f, minFee: e.target.value }))} placeholder="0"/>
          <Input label="Maximum Fee (KES)" type="number" min={0} step="0.01" value={form.maxFee}
            onChange={e => setForm((f: any) => ({ ...f, maxFee: e.target.value }))} placeholder="No max"/>
        </div>
        <Input label="GL Income Account Code" value={form.glIncomeCode}
          onChange={e => setForm((f: any) => ({ ...f, glIncomeCode: e.target.value }))} placeholder="4003"/>
        <div className="flex justify-end pt-1">
          <Button size="sm" loading={saveMutation.isPending} onClick={onSave}>Save {label}</Button>
        </div>
      </div>
    )
  }

  return (
    <>
      <button onClick={openSettings} className="text-xs text-primary hover:underline flex items-center gap-1">
        <Settings className="w-3 h-3"/> Fee Settings
      </button>
      <Modal open={open} onClose={() => setOpen(false)} title={`${accountType} Transaction Fee Settings`}
        size="lg"
        footer={<Button variant="outline" size="sm" onClick={() => setOpen(false)}>Close</Button>}>
        <div className="space-y-4">
          <p className="text-xs text-muted-foreground">Configure fees charged on {accountType} deposits and withdrawals. Fees are deducted from the member&apos;s account balance and recorded as income.</p>
          <FeeForm label="Deposit Fee" form={deposit} setForm={setDeposit} onSave={() => save('DEPOSIT', deposit)}/>
          <FeeForm label="Withdrawal Fee" form={withdrawal} setForm={setWithdrawal} onSave={() => save('WITHDRAWAL', withdrawal)}/>
        </div>
      </Modal>
    </>
  )
}
