import { useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useForm } from 'react-hook-form'
import { settingsApi } from '../../api'
import toast from 'react-hot-toast'

export default function SettingsPage() {
  const qc = useQueryClient()
  const { data, isLoading } = useQuery({
    queryKey: ['settings'],
    queryFn: () => settingsApi.get().then(r => r.data),
  })

  const { register, handleSubmit, reset } = useForm()

  useEffect(() => {
    if (data?.settings) {
      const flat: Record<string, any> = {}
      Object.entries(data.settings).forEach(([group, keys]: any) => {
        Object.entries(keys).forEach(([key, val]) => { flat[key] = val })
      })
      reset(flat)
    }
  }, [data, reset])

  const mutation = useMutation({
    mutationFn: (formData: any) => settingsApi.update(formData),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['settings'] }); toast.success('Settings saved.') },
  })

  if (isLoading) return <div className="text-slate-400 text-center py-20">Loading settings…</div>

  const Section = ({ title, children }: any) => (
    <div className="card space-y-4">
      <h2 className="font-semibold text-white border-b border-slate-700 pb-3">{title}</h2>
      {children}
    </div>
  )

  const Field = ({ label, name, type = 'text', placeholder }: any) => (
    <div>
      <label className="label">{label}</label>
      <input {...register(name)} type={type} className="input" placeholder={placeholder} />
    </div>
  )

  return (
    <div className="max-w-2xl mx-auto space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-white">Settings</h1>
        <p className="text-slate-400 text-sm mt-1">Configure your gym locker system</p>
      </div>

      <form onSubmit={handleSubmit((d) => mutation.mutate(d))} className="space-y-5">
        <Section title="Company">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <Field label="Gym Name" name="company.name" placeholder="My Gym" />
            <Field label="Currency Code" name="company.currency" placeholder="BDT" />
            <Field label="Currency Symbol" name="company.currency_symbol" placeholder="৳" />
            <Field label="Timezone" name="company.timezone" placeholder="Asia/Dhaka" />
            <Field label="Tax Rate (%)" name="company.tax_rate" type="number" placeholder="0" />
          </div>
        </Section>

        <Section title="Invoice">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <Field label="Invoice Prefix" name="invoice.prefix" placeholder="INV" />
            <Field label="Starting Number" name="invoice.starting_number" type="number" placeholder="1" />
          </div>
        </Section>

        <Section title="Rental Rules">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <Field label="Grace Period (days)" name="rental.grace_days" type="number" placeholder="3" />
            <Field label="Lost Key Fee (৳)" name="rental.lost_key_fee" type="number" placeholder="500" />
          </div>
        </Section>

        <Section title="Reminders">
          <div>
            <label className="label">Days Before Expiry to Send Reminders</label>
            <input {...register('reminders.days_before')} className="input" placeholder="[7,3,1]" />
            <p className="text-slate-500 text-xs mt-1">JSON array, e.g. [7,3,1] means 7, 3 and 1 day(s) before</p>
          </div>
          <div>
            <label className="label">Days After Expiry for Overdue Notices</label>
            <input {...register('reminders.overdue_days')} className="input" placeholder="[3,7]" />
          </div>
        </Section>

        <div className="flex justify-end">
          <button type="submit" disabled={mutation.isPending} className="btn-primary px-8">
            {mutation.isPending ? 'Saving…' : 'Save Settings'}
          </button>
        </div>
      </form>
    </div>
  )
}
