// Tạo Đề xuất mới — Phase 10.3 G-O3 (S37 2026-05-28).
// Form Header card: Title + Description + AmountEstimate + Department + ApprovalWorkflow.
// File MIRROR SHA256 identical với fe-user counterpart.
//
// Re-skin (S69): PURO/Hồ sơ-NS visual language — ui/PageHeader on top + form
// grouped into .card-accent sections with .icon-chip headers. Logic (state,
// queries, mutation, validation, bindings, submit) UNTOUCHED.
import { useState, type FormEvent } from 'react'
import { useMutation, useQuery } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import { FileText, Info, Save, Settings2, X } from 'lucide-react'
import { toast } from 'sonner'
import { PageHeader } from '@/components/ui/PageHeader'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { Label } from '@/components/ui/Label'
import { Textarea } from '@/components/ui/Textarea'
import { api } from '@/lib/api'
import { getErrorMessage } from '@/lib/apiError'
import type { CreateProposalInput } from '@/types/proposal'

interface DepartmentDto {
  id: string
  code: string
  name: string
}

interface WorkflowDto {
  id: string
  code: string
  name: string
  isUserSelectable: boolean
}

function parseVnd(s: string): number {
  return Number(s.replace(/[^\d]/g, '')) || 0
}

function formatVnd(n: number): string {
  return n > 0 ? n.toLocaleString('vi-VN') : ''
}

export function ProposalCreatePage() {
  const navigate = useNavigate()
  const [title, setTitle] = useState('')
  const [description, setDescription] = useState('')
  const [amountStr, setAmountStr] = useState('')
  const [departmentId, setDepartmentId] = useState<string>('')
  const [approvalWorkflowId, setApprovalWorkflowId] = useState<string>('')

  const departments = useQuery({
    queryKey: ['departments'],
    queryFn: async () => (await api.get<DepartmentDto[]>('/departments')).data,
  })

  // Endpoint trả AwAdminOverviewDto { types: [{ applicableType, history: [...] }] } —
  // KHÔNG phải flat array. Mirror ContractCreatePage/WorkflowAppDetail: extract bucket
  // theo applicableType=4 (Đề xuất) rồi filter isUserSelectable (admin ghim cho user pick).
  const workflows = useQuery({
    queryKey: ['approval-workflows-v2', { applicableType: 4, isUserSelectable: true }],
    queryFn: async () => {
      const res = await api.get<{ types: { applicableType: number; history: WorkflowDto[] }[] }>(
        '/approval-workflows-v2',
        { params: { applicableType: 4 } },
      )
      const bucket = res.data.types.find((t) => t.applicableType === 4)
      return (bucket?.history ?? []).filter((w) => w.isUserSelectable)
    },
  })

  const create = useMutation({
    mutationFn: async () => {
      if (!title.trim()) throw new Error('Vui lòng nhập Tiêu đề')
      const body: CreateProposalInput = {
        title: title.trim(),
        description: description.trim() || null,
        amountEstimate: amountStr ? parseVnd(amountStr) : null,
        departmentId: departmentId || null,
        approvalWorkflowId: approvalWorkflowId || null,
      }
      const res = await api.post<{ id: string }>('/proposals', body)
      return res.data.id
    },
    onSuccess: (id) => {
      toast.success('Tạo đề xuất thành công')
      navigate(`/proposals/${id}`)
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const onSubmit = (e: FormEvent) => {
    e.preventDefault()
    create.mutate()
  }

  return (
    <div className="space-y-5">
      <PageHeader
        eyebrow="Văn phòng số"
        title="Tạo Đề xuất mới"
        subtitle="Soạn đề xuất → gửi duyệt theo Quy trình admin config"
        icon={<FileText className="h-5 w-5" />}
        accent="brand"
        actions={
          <Button variant="outline" onClick={() => navigate('/proposals')}>
            <X className="mr-2 h-4 w-4" />
            Huỷ
          </Button>
        }
      />

      <form onSubmit={onSubmit} className="space-y-5">
        {/* Section 1: Nội dung đề xuất */}
        <section className="card-accent" style={{ ['--accent' as string]: 'var(--color-brand-500)' }}>
          <header className="flex items-center gap-2 border-b border-slate-100 px-5 py-3">
            <span
              className="icon-chip"
              style={{ height: '1.75rem', width: '1.75rem', ['--chip-bg' as string]: 'var(--color-brand-50)', ['--chip-fg' as string]: 'var(--color-brand-600)' }}
              aria-hidden
            >
              <FileText className="h-4 w-4" />
            </span>
            <h3 className="text-sm font-semibold tracking-tight text-brand-800">Nội dung đề xuất</h3>
          </header>
          <div className="space-y-4 p-5">
            <div>
              <Label htmlFor="title">
                Tiêu đề <span className="text-red-500">*</span>
              </Label>
              <Input
                id="title"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                maxLength={300}
                placeholder="vd. Đề xuất mua sắm máy tính cho Phòng IT"
                required
              />
            </div>

            <div>
              <Label htmlFor="description">Nội dung chi tiết</Label>
              <Textarea
                id="description"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                maxLength={5000}
                rows={6}
                placeholder="Mô tả lý do, nội dung, kết quả mong đợi..."
              />
              <div className="text-xs text-muted-foreground mt-1">{description.length}/5000</div>
            </div>
          </div>
        </section>

        {/* Section 2: Thông tin liên quan */}
        <section className="card-accent" style={{ ['--accent' as string]: 'var(--color-teal-500)' }}>
          <header className="flex items-center gap-2 border-b border-slate-100 px-5 py-3">
            <span
              className="icon-chip"
              style={{ height: '1.75rem', width: '1.75rem', ['--chip-bg' as string]: 'var(--color-teal-50)', ['--chip-fg' as string]: 'var(--color-teal-700)' }}
              aria-hidden
            >
              <Info className="h-4 w-4" />
            </span>
            <h3 className="text-sm font-semibold tracking-tight text-teal-700">Thông tin liên quan</h3>
          </header>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 p-5">
            <div>
              <Label htmlFor="amount">Số tiền dự kiến (VND)</Label>
              <Input
                id="amount"
                value={formatVnd(parseVnd(amountStr))}
                onChange={(e) => setAmountStr(e.target.value)}
                placeholder="vd. 50,000,000"
                inputMode="numeric"
              />
            </div>

            <div>
              <Label htmlFor="department">Phòng ban</Label>
              <select
                id="department"
                value={departmentId}
                onChange={(e) => setDepartmentId(e.target.value)}
                className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm"
              >
                <option value="">— Không chọn —</option>
                {departments.data?.map((d) => (
                  <option key={d.id} value={d.id}>
                    {d.code} - {d.name}
                  </option>
                ))}
              </select>
            </div>
          </div>
        </section>

        {/* Section 3: Quy trình duyệt */}
        <section className="card-accent" style={{ ['--accent' as string]: 'var(--color-violet-500)' }}>
          <header className="flex items-center gap-2 border-b border-slate-100 px-5 py-3">
            <span
              className="icon-chip"
              style={{ height: '1.75rem', width: '1.75rem', ['--chip-bg' as string]: 'var(--color-violet-50)', ['--chip-fg' as string]: 'var(--color-violet-700)' }}
              aria-hidden
            >
              <Settings2 className="h-4 w-4" />
            </span>
            <h3 className="text-sm font-semibold tracking-tight text-violet-700">Quy trình duyệt</h3>
          </header>
          <div className="space-y-2 p-5">
            <Label htmlFor="workflow">
              Quy trình duyệt <span className="text-red-500">*</span>
            </Label>
            <select
              id="workflow"
              value={approvalWorkflowId}
              onChange={(e) => setApprovalWorkflowId(e.target.value)}
              className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm"
            >
              <option value="">— Chọn quy trình —</option>
              {workflows.data?.map((w) => (
                <option key={w.id} value={w.id}>
                  {w.code} - {w.name}
                </option>
              ))}
            </select>
            <div className="text-xs text-muted-foreground mt-1">
              Chỉ hiển thị quy trình loại "Đề xuất" admin đã ghim cho user pick
            </div>
          </div>
        </section>

        <div className="flex justify-end gap-2">
          <Button type="button" variant="outline" onClick={() => navigate('/proposals')}>
            Huỷ
          </Button>
          <Button type="submit" disabled={create.isPending || !title.trim()}>
            <Save className="mr-2 h-4 w-4" />
            {create.isPending ? 'Đang lưu...' : 'Lưu nháp'}
          </Button>
        </div>
      </form>
    </div>
  )
}
