// Create / edit draft Header ngân sách. Hạng mục chỉnh ở Detail tabs sau khi save.
// CreateBudgetCommand BE chỉ cho update Tên/Mô tả/Năm khi DangSoanThao
// — Project/Department khóa sau create.
import { useEffect, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { toast } from 'sonner'
import { Wallet } from 'lucide-react'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { Label } from '@/components/ui/Label'
import { Select } from '@/components/ui/Select'
import { Textarea } from '@/components/ui/Textarea'
import { api } from '@/lib/api'
import { getErrorMessage } from '@/lib/apiError'
import type { BudgetDetailBundle } from '@/types/budget'
import type { Department, Paged, Project } from '@/types/master'

export function BudgetCreatePage() {
  const navigate = useNavigate()
  const qc = useQueryClient()
  const [sp] = useSearchParams()
  const editId = sp.get('id')
  const currentYear = new Date().getFullYear()

  const projects = useQuery({
    queryKey: ['all-projects'],
    queryFn: async () =>
      (await api.get<Paged<Project>>('/projects', { params: { pageSize: 1000 } })).data.items,
  })
  const departments = useQuery({
    queryKey: ['all-departments'],
    queryFn: async () =>
      (await api.get<Paged<Department>>('/departments', { params: { pageSize: 1000 } })).data.items,
  })
  const existing = useQuery({
    queryKey: ['budget-detail', editId],
    queryFn: async () => (await api.get<BudgetDetailBundle>(`/budgets/${editId}`)).data,
    enabled: !!editId,
  })

  const [form, setForm] = useState({
    tenNganSach: '',
    description: '',
    namNganSach: currentYear,
    projectId: '',
    departmentId: '',
  })

  useEffect(() => {
    if (existing.data) {
      setForm({
        tenNganSach: existing.data.tenNganSach,
        description: existing.data.description ?? '',
        namNganSach: existing.data.namNganSach,
        projectId: existing.data.projectId,
        departmentId: existing.data.departmentId ?? '',
      })
    }
  }, [existing.data])

  const mut = useMutation({
    mutationFn: async () => {
      if (editId) {
        return api.put(`/budgets/${editId}`, {
          id: editId,
          tenNganSach: form.tenNganSach,
          description: form.description || null,
          namNganSach: form.namNganSach,
        })
      }
      return api.post<{ id: string }>('/budgets', {
        tenNganSach: form.tenNganSach,
        description: form.description || null,
        namNganSach: form.namNganSach,
        projectId: form.projectId,
        departmentId: form.departmentId || null,
      })
    },
    onSuccess: res => {
      toast.success(editId ? 'Đã lưu.' : 'Đã tạo ngân sách.')
      qc.invalidateQueries({ queryKey: ['budget-list'] })
      const id = editId ?? (res as { data: { id: string } }).data.id
      navigate(`/budgets?id=${id}`)
    },
    onError: e => toast.error(getErrorMessage(e)),
  })

  return (
    <div className="space-y-4 p-6">
      <header className="flex items-center gap-2">
        <Wallet className="h-5 w-5 text-slate-500" />
        <h1 className="text-base font-semibold tracking-tight text-slate-900">
          {editId ? 'Sửa header ngân sách' : 'Tạo ngân sách mới'}
        </h1>
      </header>

      <div className="max-w-2xl space-y-4 rounded-lg border border-slate-200 bg-white p-6 shadow-sm">
        <div>
          <Label>Tên ngân sách *</Label>
          <Input
            value={form.tenNganSach}
            onChange={e => setForm({ ...form, tenNganSach: e.target.value })}
            placeholder="vd Ngân sách thi công Block A — FLOCK 01"
          />
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div>
            <Label>Năm ngân sách *</Label>
            <Input
              type="number"
              min={2020}
              max={2100}
              value={form.namNganSach}
              onChange={e => setForm({ ...form, namNganSach: Number(e.target.value) })}
            />
          </div>
          <div>
            <Label>Phòng ban</Label>
            <Select
              value={form.departmentId}
              disabled={!!editId}
              onChange={e => setForm({ ...form, departmentId: e.target.value })}
            >
              <option value="">— (tùy chọn)</option>
              {departments.data?.map(d => (
                <option key={d.id} value={d.id}>{d.code} — {d.name}</option>
              ))}
            </Select>
          </div>
        </div>

        <div>
          <Label>Dự án *</Label>
          <Select
            value={form.projectId}
            disabled={!!editId}
            onChange={e => setForm({ ...form, projectId: e.target.value })}
          >
            <option value="">-- Chọn --</option>
            {projects.data?.map(p => (
              <option key={p.id} value={p.id}>{p.code} — {p.name}</option>
            ))}
          </Select>
          {editId && (
            <p className="mt-1 text-[11px] text-slate-500">Dự án + Phòng ban khóa sau khi tạo.</p>
          )}
        </div>

        <div>
          <Label>Mô tả</Label>
          <Textarea
            rows={4}
            value={form.description}
            onChange={e => setForm({ ...form, description: e.target.value })}
            placeholder="Ghi chú ngân sách, phạm vi sử dụng, ràng buộc..."
          />
        </div>

        <div className="flex justify-end gap-2">
          <Button variant="ghost" onClick={() => navigate(-1)}>Hủy</Button>
          <Button
            onClick={() => mut.mutate()}
            disabled={!form.tenNganSach || !form.projectId || mut.isPending}
          >
            {editId ? 'Lưu' : 'Tạo ngân sách'}
          </Button>
        </div>
      </div>
    </div>
  )
}
