// Page Create Hồ sơ Nhân sự — Header form minimal.
// Phase 10.1 G-H1 Phase 1 (S33 Task 5): chỉ Header field tối thiểu để link
// User → EmployeeProfile. Section còn lại edit sau qua DetailPanel (Phase 1.5).
import { useState, type FormEvent } from 'react'
import { useMutation, useQuery } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import { toast } from 'sonner'
import { UserPlus } from 'lucide-react'
import { Input } from '@/components/ui/Input'
import { Select } from '@/components/ui/Select'
import { Label } from '@/components/ui/Label'
import { Button } from '@/components/ui/Button'
import { api } from '@/lib/api'
import { getErrorMessage } from '@/lib/apiError'
import type { Paged } from '@/types/master'
import { EmployeeStatus, EmployeeStatusLabel, Gender, GenderLabel } from '@/types/employee'

// User dropdown list response (mirror BE UsersController list shape — id/fullName/email subset).
type UserOption = {
  id: string
  fullName: string | null
  email: string
}

type CreateForm = {
  userId: string
  employeeStatus: string
  hireDate: string
  dateOfBirth: string
  gender: string
  phone: string
  nationality: string
}

const todayIso = () => new Date().toISOString().slice(0, 10)

const initial: CreateForm = {
  userId: '',
  employeeStatus: String(EmployeeStatus.Active),
  hireDate: todayIso(),
  dateOfBirth: '',
  gender: '',
  phone: '',
  nationality: 'Việt Nam',
}

const PHONE_RE = /^0\d{9,10}$/
const isValidPhone = (s: string) => !s || PHONE_RE.test(s.replace(/[\s\-.]/g, ''))

export function EmployeeCreatePage() {
  const navigate = useNavigate()
  const [form, setForm] = useState<CreateForm>(initial)

  // Lấy list user để pick — pageSize lớn cho admin pick dễ.
  const users = useQuery({
    queryKey: ['users-for-employee-create'],
    queryFn: async () =>
      (await api.get<Paged<UserOption>>('/users', { params: { page: 1, pageSize: 200 } })).data.items,
  })

  const create = useMutation({
    mutationFn: async () => {
      const body = {
        userId: form.userId,
        employeeStatus: Number(form.employeeStatus),
        hireDate: form.hireDate || null,
        dateOfBirth: form.dateOfBirth || null,
        gender: form.gender ? Number(form.gender) : null,
        phone: form.phone.trim() || null,
        nationality: form.nationality.trim() || null,
      }
      return (await api.post<{ id: string }>('/employees', body)).data
    },
    onSuccess: data => {
      toast.success('Đã tạo hồ sơ NV.')
      navigate(`/employees?id=${data.id}`)
    },
    onError: e => toast.error(getErrorMessage(e)),
  })

  function submit(e: FormEvent) {
    e.preventDefault()
    if (!form.userId) {
      toast.error('Vui lòng chọn user.')
      return
    }
    if (!isValidPhone(form.phone)) {
      toast.error('SĐT không hợp lệ (10-11 số, bắt đầu bằng 0).')
      return
    }
    create.mutate()
  }

  return (
    <div className="mx-auto max-w-2xl space-y-4 p-6">
      <header className="flex items-center gap-2">
        <UserPlus className="h-5 w-5 text-brand-600" />
        <h1 className="text-base font-semibold tracking-tight text-slate-900">Tạo Hồ sơ Nhân sự mới</h1>
      </header>

      <form onSubmit={submit} className="space-y-4 rounded-lg border border-slate-200 bg-white p-6 shadow-sm">
        <div>
          <Label htmlFor="userId">User <span className="text-red-500">*</span></Label>
          <Select
            id="userId"
            value={form.userId}
            onChange={e => setForm(f => ({ ...f, userId: e.target.value }))}
            required
          >
            <option value="">— Chọn user —</option>
            {(users.data ?? []).map(u => (
              <option key={u.id} value={u.id}>
                {u.fullName ? `${u.fullName} (${u.email})` : u.email}
              </option>
            ))}
          </Select>
          <p className="mt-1 text-xs text-slate-500">
            Mỗi user chỉ được link với 1 hồ sơ NV. Tạo user mới ở mục System &gt; Users nếu thiếu.
          </p>
        </div>

        <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
          <div>
            <Label htmlFor="employeeStatus">Trạng thái</Label>
            <Select
              id="employeeStatus"
              value={form.employeeStatus}
              onChange={e => setForm(f => ({ ...f, employeeStatus: e.target.value }))}
            >
              <option value={String(EmployeeStatus.Active)}>{EmployeeStatusLabel[EmployeeStatus.Active]}</option>
              <option value={String(EmployeeStatus.OnLeave)}>{EmployeeStatusLabel[EmployeeStatus.OnLeave]}</option>
              <option value={String(EmployeeStatus.Resigned)}>{EmployeeStatusLabel[EmployeeStatus.Resigned]}</option>
            </Select>
          </div>

          <div>
            <Label htmlFor="hireDate">Ngày vào làm</Label>
            <Input
              id="hireDate"
              type="date"
              value={form.hireDate}
              onChange={e => setForm(f => ({ ...f, hireDate: e.target.value }))}
            />
          </div>

          <div>
            <Label htmlFor="gender">Giới tính</Label>
            <Select
              id="gender"
              value={form.gender}
              onChange={e => setForm(f => ({ ...f, gender: e.target.value }))}
            >
              <option value="">—</option>
              <option value={String(Gender.Male)}>{GenderLabel[Gender.Male]}</option>
              <option value={String(Gender.Female)}>{GenderLabel[Gender.Female]}</option>
              <option value={String(Gender.Other)}>{GenderLabel[Gender.Other]}</option>
            </Select>
          </div>

          <div>
            <Label htmlFor="dateOfBirth">Ngày sinh</Label>
            <Input
              id="dateOfBirth"
              type="date"
              value={form.dateOfBirth}
              onChange={e => setForm(f => ({ ...f, dateOfBirth: e.target.value }))}
            />
          </div>

          <div>
            <Label htmlFor="phone">SĐT</Label>
            <Input
              id="phone"
              value={form.phone}
              onChange={e => setForm(f => ({ ...f, phone: e.target.value }))}
              placeholder="0912345678"
            />
          </div>

          <div>
            <Label htmlFor="nationality">Quốc tịch</Label>
            <Input
              id="nationality"
              value={form.nationality}
              onChange={e => setForm(f => ({ ...f, nationality: e.target.value }))}
            />
          </div>
        </div>

        <div className="flex justify-end gap-2 border-t border-slate-100 pt-4">
          <Button type="button" variant="outline" onClick={() => navigate(-1)} disabled={create.isPending}>
            Huỷ
          </Button>
          <Button type="submit" disabled={create.isPending}>
            {create.isPending ? 'Đang lưu...' : 'Tạo hồ sơ'}
          </Button>
        </div>

        <p className="text-xs text-slate-400">
          Các thông tin chi tiết (giấy tờ, địa chỉ, lương, kỹ năng, ...) có thể bổ sung ở mục Sửa hồ sơ sau khi tạo.
        </p>
      </form>
    </div>
  )
}
