"use client"

import { useEffect, useState } from "react"
import { Plus } from "lucide-react"

import { payrollStatutorySettingsApi, taxSlabsApi } from "@/lib/api/payroll"
import { errorMessage } from "@/lib/error-map"
import { PayrollStatutorySetting, TaxSlab } from "@/types/hrm"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { toast } from "@/components/ui/toast"

export default function StatutorySettingsPage() {
  const [settings, setSettings] = useState<PayrollStatutorySetting[]>([])
  const [slabs, setSlabs] = useState<TaxSlab[]>([])
  const [error, setError] = useState<string | null>(null)

  const [settingOpen, setSettingOpen] = useState(false)
  const [epfEmployeeRate, setEpfEmployeeRate] = useState(0.08)
  const [epfEmployerRate, setEpfEmployerRate] = useState(0.12)
  const [etfEmployerRate, setEtfEmployerRate] = useState(0.03)
  const [otMultiplierDefault, setOtMultiplierDefault] = useState(1.5)
  const [effectiveFrom, setEffectiveFrom] = useState("")

  const [slabOpen, setSlabOpen] = useState(false)
  const [slabEffectiveFrom, setSlabEffectiveFrom] = useState("")
  const [lowerBound, setLowerBound] = useState(0)
  const [upperBound, setUpperBound] = useState<string>("")
  const [rate, setRate] = useState(0.06)
  const [submitting, setSubmitting] = useState(false)

  function load() {
    Promise.all([payrollStatutorySettingsApi.list(), taxSlabsApi.list()])
      .then(([s, t]) => { setSettings(s); setSlabs(t) })
      .catch((err) => setError(errorMessage(err)))
  }
  useEffect(load, [])

  async function createSetting() {
    if (!effectiveFrom) { toast.error("Effective date is required"); return }
    setSubmitting(true)
    try {
      await payrollStatutorySettingsApi.create({ epfEmployeeRate, epfEmployerRate, etfEmployerRate, otMultiplierDefault, effectiveFrom })
      toast.success("Statutory setting saved")
      setSettingOpen(false)
      load()
    } catch (err) {
      toast.error("Could not save", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  async function createSlab() {
    if (!slabEffectiveFrom) { toast.error("Effective date is required"); return }
    setSubmitting(true)
    try {
      await taxSlabsApi.create({
        effectiveFrom: slabEffectiveFrom,
        lowerBound,
        upperBound: upperBound.trim() === "" ? null : Number(upperBound),
        rate,
      })
      toast.success("Tax slab created")
      setSlabOpen(false)
      load()
    } catch (err) {
      toast.error("Could not create tax slab", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="flex flex-col gap-8">
      <div>
        <h1 className="text-2xl font-bold text-foreground">Statutory Settings</h1>
        <p className="text-base text-muted-foreground">EPF/ETF rates and tax slabs — effective-dated since these change with government policy.</p>
      </div>

      {error && <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-5 text-base text-destructive">{error}</div>}

      <section className="flex flex-col gap-4">
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <h2 className="text-lg font-semibold text-foreground">EPF / ETF Rates</h2>
          <Dialog open={settingOpen} onOpenChange={setSettingOpen}>
            <DialogTrigger render={<Button size="sm"><Plus className="size-4" />New Setting</Button>} />
            <DialogContent className="sm:max-w-sm">
              <DialogHeader className="items-center text-center">
                <DialogTitle>New Statutory Setting</DialogTitle>
                <DialogDescription>Supersedes the current open-ended setting from this date.</DialogDescription>
              </DialogHeader>
              <FieldGroup>
                <Field><FieldLabel>Effective from</FieldLabel><Input type="date" value={effectiveFrom} onChange={(e) => setEffectiveFrom(e.target.value)} /></Field>
                <Field><FieldLabel>EPF employee rate (0-1)</FieldLabel><Input type="number" step="0.001" value={epfEmployeeRate} onChange={(e) => setEpfEmployeeRate(Number(e.target.value))} /></Field>
                <Field><FieldLabel>EPF employer rate (0-1)</FieldLabel><Input type="number" step="0.001" value={epfEmployerRate} onChange={(e) => setEpfEmployerRate(Number(e.target.value))} /></Field>
                <Field><FieldLabel>ETF employer rate (0-1)</FieldLabel><Input type="number" step="0.001" value={etfEmployerRate} onChange={(e) => setEtfEmployerRate(Number(e.target.value))} /></Field>
                <Field><FieldLabel>Default OT multiplier</FieldLabel><Input type="number" step="0.1" value={otMultiplierDefault} onChange={(e) => setOtMultiplierDefault(Number(e.target.value))} /></Field>
              </FieldGroup>
              <div className="flex flex-col-reverse gap-3 pt-2 sm:flex-row sm:justify-center">
                <Button variant="outline" className="w-full sm:w-auto sm:min-w-32" onClick={() => setSettingOpen(false)} disabled={submitting}>Cancel</Button>
                <Button className="w-full sm:w-auto sm:min-w-32" onClick={createSetting} disabled={submitting}>{submitting ? "Saving…" : "Save"}</Button>
              </div>
            </DialogContent>
          </Dialog>
        </div>
        <Table className="text-base">
          <TableHeader>
            <TableRow>
              <TableHead className="h-12 px-3 text-sm">Effective from</TableHead>
              <TableHead className="h-12 px-3 text-sm">EPF (Employee)</TableHead>
              <TableHead className="h-12 px-3 text-sm">EPF (Employer)</TableHead>
              <TableHead className="h-12 px-3 text-sm">ETF (Employer)</TableHead>
              <TableHead className="h-12 px-3 text-sm">OT multiplier</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {settings.map((s) => (
              <TableRow key={s.payrollStatutorySettingId}>
                <TableCell className="px-3 py-3.5">{new Date(s.effectiveFrom).toLocaleDateString()}{s.effectiveTo ? ` – ${new Date(s.effectiveTo).toLocaleDateString()}` : " (current)"}</TableCell>
                <TableCell className="px-3 py-3.5">{(s.epfEmployeeRate * 100).toFixed(1)}%</TableCell>
                <TableCell className="px-3 py-3.5">{(s.epfEmployerRate * 100).toFixed(1)}%</TableCell>
                <TableCell className="px-3 py-3.5">{(s.etfEmployerRate * 100).toFixed(1)}%</TableCell>
                <TableCell className="px-3 py-3.5">{s.otMultiplierDefault}x</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </section>

      <section className="flex flex-col gap-4">
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <h2 className="text-lg font-semibold text-foreground">Tax Slabs</h2>
          <Dialog open={slabOpen} onOpenChange={setSlabOpen}>
            <DialogTrigger render={<Button size="sm"><Plus className="size-4" />New Slab</Button>} />
            <DialogContent className="sm:max-w-sm">
              <DialogHeader className="items-center text-center">
                <DialogTitle>New Tax Slab</DialogTitle>
                <DialogDescription>Leave upper bound empty for &quot;and above&quot;.</DialogDescription>
              </DialogHeader>
              <FieldGroup>
                <Field><FieldLabel>Effective from</FieldLabel><Input type="date" value={slabEffectiveFrom} onChange={(e) => setSlabEffectiveFrom(e.target.value)} /></Field>
                <Field><FieldLabel>Lower bound</FieldLabel><Input type="number" min={0} value={lowerBound} onChange={(e) => setLowerBound(Number(e.target.value))} /></Field>
                <Field><FieldLabel>Upper bound (optional)</FieldLabel><Input type="number" value={upperBound} onChange={(e) => setUpperBound(e.target.value)} placeholder="And above" /></Field>
                <Field><FieldLabel>Rate (0-1)</FieldLabel><Input type="number" step="0.01" value={rate} onChange={(e) => setRate(Number(e.target.value))} /></Field>
              </FieldGroup>
              <div className="flex flex-col-reverse gap-3 pt-2 sm:flex-row sm:justify-center">
                <Button variant="outline" className="w-full sm:w-auto sm:min-w-32" onClick={() => setSlabOpen(false)} disabled={submitting}>Cancel</Button>
                <Button className="w-full sm:w-auto sm:min-w-32" onClick={createSlab} disabled={submitting}>{submitting ? "Creating…" : "Create"}</Button>
              </div>
            </DialogContent>
          </Dialog>
        </div>
        <Table className="text-base">
          <TableHeader>
            <TableRow>
              <TableHead className="h-12 px-3 text-sm">Effective from</TableHead>
              <TableHead className="h-12 px-3 text-sm">Range</TableHead>
              <TableHead className="h-12 px-3 text-sm">Rate</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {slabs.map((s) => (
              <TableRow key={s.taxSlabId}>
                <TableCell className="px-3 py-3.5">{new Date(s.effectiveFrom).toLocaleDateString()}</TableCell>
                <TableCell className="px-3 py-3.5">{s.lowerBound.toLocaleString()} – {s.upperBound ? s.upperBound.toLocaleString() : "and above"}</TableCell>
                <TableCell className="px-3 py-3.5">{(s.rate * 100).toFixed(1)}%</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </section>
    </div>
  )
}
