"use client"

import { useMemo, useState, useRef, useEffect } from "react"
import { useRouter } from "next/navigation"

import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Dropdown } from "@/components/ui/dropdown"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { cn } from "@/lib/utils"

import type { EmployeeInput } from "@/features/employees/schema"

type Option = { id: string; name: string }
type ShiftOption = { id: string; name: string }
type LeaveTypeOption = { id: string; name: string }
type BranchOption = { id: string; name: string }
type ManagerOption = { id: string; fullName: string }

type EmployeeFormProps = {
  initialData?: EmployeeInput & { id?: string }
  branches: BranchOption[]
  shifts: ShiftOption[]
  leaveTypes: LeaveTypeOption[]
  hasUserAccount: boolean
  currencyCode: string
  decimalPlaces: number
}

function toDateInputValue(d?: Date | string | null) {
  if (!d) return ""
  const date = d instanceof Date ? d : new Date(d)
  if (Number.isNaN(date.getTime())) return ""
  return date.toISOString().slice(0, 10)
}

// ─── File Upload Field ────────────────────────────────────────────────────────

type UploadedFile = { name: string; url: string; size: number; type: string }

function FileUploadField({
  label, accept = ".pdf,.jpg,.jpeg,.png", value, onChange,
}: {
  label: string; accept?: string
  value: UploadedFile | null
  onChange: (file: UploadedFile | null) => void
}) {
  const inputRef = useRef<HTMLInputElement>(null)
  const [dragging, setDragging] = useState(false)

  function handleFile(file: File) {
    const reader = new FileReader()
    reader.onload = (e) => onChange({ name: file.name, url: e.target?.result as string, size: file.size, type: file.type })
    reader.readAsDataURL(file)
  }

  const isImage = value?.type.startsWith("image/")

  return (
    <div className="space-y-2">
      <Label>{label} <span className="text-muted-foreground text-xs">(optional)</span></Label>
      {value ? (
        <div className="flex items-center gap-3 rounded-lg border bg-muted/30 p-3">
          <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-background border">
            {isImage ? (
              <img src={value.url} alt={value.name} className="h-10 w-10 rounded-md object-cover" />
            ) : (
              <svg className="h-5 w-5 text-red-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
                <polyline points="14 2 14 8 20 8" />
                <line x1="9" y1="13" x2="15" y2="13" />
                <line x1="9" y1="17" x2="12" y2="17" />
              </svg>
            )}
          </div>
          <div className="min-w-0 flex-1">
            <p className="truncate text-sm font-medium">{value.name}</p>
            <p className="text-xs text-muted-foreground">{(value.size / 1024).toFixed(1)} KB</p>
          </div>
          <button type="button" onClick={() => onChange(null)} className="shrink-0 rounded-md p-1 text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12" /></svg>
          </button>
        </div>
      ) : (
        <div
          onDragOver={(e) => { e.preventDefault(); setDragging(true) }}
          onDragLeave={() => setDragging(false)}
          onDrop={(e) => { e.preventDefault(); setDragging(false); const f = e.dataTransfer.files[0]; if (f) handleFile(f) }}
          onClick={() => inputRef.current?.click()}
          className={cn(
            "flex cursor-pointer flex-col items-center justify-center gap-1.5 rounded-lg border-2 border-dashed px-4 py-5 text-center transition-colors",
            dragging ? "border-primary bg-primary/5" : "border-input bg-muted/20 hover:border-primary/50 hover:bg-muted/40"
          )}
        >
          <svg className="h-7 w-7 text-muted-foreground" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
            <polyline points="17 8 12 3 7 8" />
            <line x1="12" y1="3" x2="12" y2="15" />
          </svg>
          <p className="text-xs text-muted-foreground">
            <span className="font-medium text-foreground">Click to upload</span> or drag & drop
          </p>
          <p className="text-[10px] text-muted-foreground">PDF, JPG, PNG</p>
          <input ref={inputRef} type="file" accept={accept} className="hidden"
            onChange={(e) => { const f = e.target.files?.[0]; if (f) handleFile(f); e.target.value = "" }} />
        </div>
      )}
    </div>
  )
}

// ─── Tab bar ─────────────────────────────────────────────────────────────────

function TabBar({ tabs, active, onChange }: { tabs: string[]; active: string; onChange: (t: string) => void }) {
  return (
    <div className="flex gap-1 rounded-lg border bg-muted/40 p-1 w-fit">
      {tabs.map((t) => (
        <button key={t} type="button" onClick={() => onChange(t)}
          className={cn(
            "rounded-md px-4 py-1.5 text-sm font-medium transition-colors",
            active === t ? "bg-background shadow-sm text-foreground" : "text-muted-foreground hover:text-foreground"
          )}
        >{t}</button>
      ))}
    </div>
  )
}

// ─── Main Form ────────────────────────────────────────────────────────────────

export default function EmployeeForm({
  initialData,
  branches,
  shifts,
  leaveTypes,
  hasUserAccount,
  currencyCode,
  decimalPlaces,
}: EmployeeFormProps) {
  const formatCurrency = (amount: number) =>
    new Intl.NumberFormat("en-US", { style: "currency", currency: currencyCode, minimumFractionDigits: decimalPlaces, maximumFractionDigits: decimalPlaces }).format(amount)

  const router = useRouter()
  const [tab, setTab] = useState("Employee Info")
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")

  // ── Cascading selections ──────────────────────────────────────────────────
  const [branchId, setBranchId] = useState(initialData?.branchId || "")
  const [departmentId, setDepartmentId] = useState(initialData?.departmentId || "")
  const [subDepartmentId, setSubDepartmentId] = useState(initialData?.subDepartmentId || "")
  const [reportingManagerId, setReportingManagerId] = useState(initialData?.reportingManagerId || "")

  // ── Dynamic lists ─────────────────────────────────────────────────────────
  const [departments, setDepartments] = useState<Option[]>([])
  const [subDepartments, setSubDepartments] = useState<Option[]>([])
  const [managers, setManagers] = useState<ManagerOption[]>([])
  const [depsLoading, setDepsLoading] = useState(false)
  const [subDepsLoading, setSubDepsLoading] = useState(false)
  const [managersLoading, setManagersLoading] = useState(false)

  // ── Personal fields ───────────────────────────────────────────────────────
  const [fullName, setFullName] = useState(initialData?.fullName || "")
  const [dob, setDob] = useState(toDateInputValue(initialData?.dob))
  const [joiningDate, setJoiningDate] = useState(toDateInputValue(initialData?.joiningDate))
  const [email, setEmail] = useState(initialData?.email || "")
  const [phone, setPhone] = useState(initialData?.phone || "")
  const [position, setPosition] = useState(initialData?.position || "")
  const [nationality, setNationality] = useState(initialData?.nationality || "")
  const [address, setAddress] = useState(initialData?.address || "")
  const [description, setDescription] = useState(initialData?.description || "")
  const [createUser, setCreateUser] = useState(hasUserAccount ? true : Boolean(initialData?.createUser))
  const [userPassword, setUserPassword] = useState("")
  const [shiftId, setShiftId] = useState(initialData?.shifts?.[0]?.shiftId || "")
  const [shiftEffectiveFrom, setShiftEffectiveFrom] = useState(toDateInputValue(initialData?.shifts?.[0]?.effectiveFrom))
  const [zktecoId, setZktecoId] = useState(initialData?.zktecoId || "")

  const [avatarFile, setAvatarFile] = useState<UploadedFile | null>(
    initialData?.avatarUrl
      ? { url: initialData.avatarUrl, name: "avatar", size: 0, type: "image/jpeg" }
      : null
  )

  // ── Document fields ───────────────────────────────────────────────────────
  const [civilId, setCivilId] = useState(initialData?.civilId || "")
  const [civilIdExpiry, setCivilIdExpiry] = useState(toDateInputValue(initialData?.document?.civilIdExpiry))
  const [passportNumber, setPassportNumber] = useState(initialData?.document?.passportNumber || "")
  const [passportExpiry, setPassportExpiry] = useState(toDateInputValue(initialData?.document?.passportExpiry))
  const [civilIdFile, setCivilIdFile] = useState<UploadedFile | null>(
    initialData?.document?.civilIdFileUrl
      ? { url: initialData.document.civilIdFileUrl, name: initialData.document.civilIdFileName ?? "civil-id", size: 0, type: initialData.document.civilIdFileUrl.startsWith("data:image") ? "image/jpeg" : "application/pdf" }
      : null
  )
  const [passportFile, setPassportFile] = useState<UploadedFile | null>(
    initialData?.document?.passportFileUrl
      ? { url: initialData.document.passportFileUrl, name: initialData.document.passportFileName ?? "passport", size: 0, type: initialData.document.passportFileUrl.startsWith("data:image") ? "image/jpeg" : "application/pdf" }
      : null
  )
  const [otherFile, setOtherFile] = useState<UploadedFile | null>(
    initialData?.document?.otherFileUrl
      ? { url: initialData.document.otherFileUrl, name: initialData.document.otherFileName ?? "document", size: 0, type: initialData.document.otherFileUrl.startsWith("data:image") ? "image/jpeg" : "application/pdf" }
      : null
  )

  // ── Salary ────────────────────────────────────────────────────────────────
  const initialSalary = initialData?.salaryComponents?.length
    ? initialData.salaryComponents
    : [{ category: "Base Salary", amount: 0 }]

  const [salaryComponents, setSalaryComponents] = useState(
    initialSalary.map((s) => ({ category: s.category, amount: String(s.amount ?? 0) }))
  )
  const [annualDays, setAnnualDays] = useState(
    initialData?.leaveAllowance?.annualDays !== undefined ? String(initialData.leaveAllowance.annualDays) : "30"
  )
  const [sickDays, setSickDays] = useState(
    initialData?.leaveAllowance?.sickDays !== undefined ? String(initialData.leaveAllowance.sickDays) : "15"
  )
  const [leaveAllowances, setLeaveAllowances] = useState(
    initialData?.leaveAllowances?.length
      ? initialData.leaveAllowances.map((l) => ({ leaveTypeId: l.leaveTypeId ?? "", leaveTypeName: l.leaveTypeName ?? "", days: String(l.days ?? 0) }))
      : []
  )

  const totalPayable = useMemo(() => salaryComponents.reduce((sum, s) => {
    const n = Number(s.amount); return sum + (Number.isFinite(n) ? n : 0)
  }, 0), [salaryComponents])

  // ── Fetch departments when branch changes ─────────────────────────────────
  useEffect(() => {
    if (!branchId) { setDepartments([]); setSubDepartments([]); setManagers([]); setDepartmentId(""); setSubDepartmentId(""); setReportingManagerId(""); return }
    setDepsLoading(true)
    setDepartmentId("")
    setSubDepartmentId("")
    setSubDepartments([])
    fetch(`/api/departments?branchId=${branchId}`)
      .then(r => r.json())
      .then(setDepartments)
      .catch(() => setDepartments([]))
      .finally(() => setDepsLoading(false))
  }, [branchId])

  // ── Fetch sub-departments when department changes ─────────────────────────
  useEffect(() => {
    if (!departmentId) { setSubDepartments([]); setSubDepartmentId(""); return }
    setSubDepsLoading(true)
    setSubDepartmentId("")
    fetch(`/api/departments/sub?departmentId=${departmentId}`)
      .then(r => r.json())
      .then(setSubDepartments)
      .catch(() => setSubDepartments([]))
      .finally(() => setSubDepsLoading(false))
  }, [departmentId])

  // Replace the managers useEffect:
  useEffect(() => {
    setManagersLoading(true)
    fetch(`/api/employees/managers`)
      .then(r => r.json())
      .then(data => setManagers(Array.isArray(data) ? data : []))
      .catch(() => setManagers([]))
      .finally(() => setManagersLoading(false))
  }, [])

  // ── Dropdown option lists ─────────────────────────────────────────────────
  const branchOptions = branches.map(b => ({ value: b.id, label: b.name }))
  const departmentOptions = departments.map(d => ({ value: d.id, label: d.name }))
  const subDepartmentOptions = subDepartments.map(d => ({ value: d.id, label: d.name }))
  const managerOptions = managers.map(m => ({ value: m.id, label: m.fullName }))
  const shiftOptions = shifts.map(s => ({ value: s.id, label: s.name }))
  const leaveTypeOptions = leaveTypes.map(t => ({ value: t.id, label: t.name }))

  // ── Salary helpers ────────────────────────────────────────────────────────
  function addSalaryComponent() { setSalaryComponents(p => [...p, { category: "", amount: "0" }]) }
  function updateSalaryComponent(idx: number, patch: Partial<{ category: string; amount: string }>) {
    setSalaryComponents(p => p.map((s, i) => i === idx ? { ...s, ...patch } : s))
  }
  function removeSalaryComponent(idx: number) { setSalaryComponents(p => p.filter((_, i) => i !== idx)) }

  // ── Leave helpers ─────────────────────────────────────────────────────────
  function addLeaveAllowance() { setLeaveAllowances(p => [...p, { leaveTypeId: "", leaveTypeName: "", days: "0" }]) }
  function updateLeaveAllowance(idx: number, patch: Partial<{ leaveTypeId: string; leaveTypeName: string; days: string }>) {
    setLeaveAllowances(p => p.map((l, i) => i === idx ? { ...l, ...patch } : l))
  }
  function removeLeaveAllowance(idx: number) { setLeaveAllowances(p => p.filter((_, i) => i !== idx)) }

  // ── Submit ────────────────────────────────────────────────────────────────
  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setLoading(true)
    setError("")
    try {
      if (!hasUserAccount && createUser && !userPassword) throw new Error("Password is required to create employee login")

      const body: EmployeeInput = {
        fullName,
        dob: dob ? new Date(dob) : undefined,
        joiningDate: joiningDate ? new Date(joiningDate) : undefined,
        email: email || undefined,
        phone: phone || undefined,
        civilId: civilId || undefined,
        nationality: nationality || undefined,
        address: address || undefined,
        position: position || undefined,
        reportingManagerId: reportingManagerId || undefined,
        departmentId: departmentId || undefined,
        subDepartmentId: subDepartmentId || undefined,
        branchId: branchId || undefined,
        description: description || undefined,
        avatarUrl: avatarFile?.url || undefined,
        zktecoId: zktecoId || undefined,
        shifts: shiftId ? [{ shiftId, effectiveFrom: shiftEffectiveFrom ? new Date(shiftEffectiveFrom) : undefined }] : [],
        document: {
          civilIdExpiry: civilIdExpiry ? new Date(civilIdExpiry) : undefined,
          passportNumber: passportNumber || undefined,
          passportExpiry: passportExpiry ? new Date(passportExpiry) : undefined,
          civilIdFileUrl: civilIdFile?.url || undefined,
          civilIdFileName: civilIdFile?.name || undefined,
          passportFileUrl: passportFile?.url || undefined,
          passportFileName: passportFile?.name || undefined,
          otherFileUrl: otherFile?.url || undefined,
          otherFileName: otherFile?.name || undefined,
        },
        salaryComponents: salaryComponents
          .filter(s => s.category.trim().length > 0)
          .map(s => ({ category: s.category, amount: Number(s.amount || 0) })),
        leaveAllowance: { annualDays: Number(annualDays || 0), sickDays: Number(sickDays || 0) },
        leaveAllowances: leaveAllowances
          .filter(l => (l.leaveTypeId || l.leaveTypeName) && Number(l.days) >= 0)
          .map(l => ({ leaveTypeId: l.leaveTypeId || undefined, leaveTypeName: l.leaveTypeName || undefined, days: Number(l.days || 0) })),
        createUser,
        userPassword: createUser && userPassword ? userPassword : undefined,
      }

      const id = initialData?.id
      const url = id ? `/api/employees/${id}` : "/api/employees"
      const method = id ? "PUT" : "POST"

      const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })
      if (!res.ok) {
        const data = await res.json().catch(() => null)
        const detailMsg = data?.details
          ? (Array.isArray(data.details)
            ? data.details.map((d: { path?: string[]; message?: string }) => `${d.path?.join(".")}: ${d.message}`).join(", ")
            : String(data.details))
          : ""
        throw new Error(data?.error + (detailMsg ? ` - ${detailMsg}` : "") || "Failed to save employee")
      }

      router.push("/employees")
      router.refresh()
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Failed to save employee")
    } finally {
      setLoading(false)
    }
  }

  // ─── Render ───────────────────────────────────────────────────────────────
  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {error && (
        <div className="rounded-lg border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive">{error}</div>
      )}

      <div className="flex items-center justify-between gap-4 flex-wrap">
        <TabBar tabs={["Employee Info", "Documents"]} active={tab} onChange={setTab} />
        <Button type="submit" disabled={loading}>{loading ? "Saving..." : "Save"}</Button>
      </div>

      {/* ══ TAB 1 — Employee Info ══ */}
      {tab === "Employee Info" && (
        <>
          {/* Personal Info */}
          <Card>
            <CardHeader className="flex-row items-center justify-between">
              <CardTitle className="text-sm font-medium">Personal Information</CardTitle>
            </CardHeader>
            <CardContent className="grid gap-4 md:grid-cols-4">
              <div className="md:col-span-1">
                <div className="flex flex-col items-start gap-2">
                  <div
                    className="relative h-24 w-24 cursor-pointer group"
                    onClick={() => document.getElementById("avatar-input")?.click()}
                  >
                    {avatarFile ? (
                      <img
                        src={avatarFile.url}
                        alt="Avatar"
                        className="h-24 w-24 rounded-full object-cover border-2 border-border"
                      />
                    ) : (
                      <div className="flex h-24 w-24 items-center justify-center rounded-full bg-muted text-muted-foreground border-2 border-dashed border-border group-hover:border-primary transition-colors">
                        <svg className="h-8 w-8 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
                            d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                        </svg>
                      </div>
                    )}
                    <div className="absolute inset-0 rounded-full bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                      <svg className="h-6 w-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                          d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" />
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
                      </svg>
                    </div>
                    <input
                      id="avatar-input"
                      type="file"
                      accept="image/*"
                      className="hidden"
                      onChange={(e) => {
                        const file = e.target.files?.[0]
                        if (!file) return
                        const reader = new FileReader()
                        reader.onload = (ev) => setAvatarFile({
                          name: file.name,
                          url: ev.target?.result as string,
                          size: file.size,
                          type: file.type,
                        })
                        reader.readAsDataURL(file)
                        e.target.value = ""
                      }}
                    />
                  </div>
                  {avatarFile && (
                    <button
                      type="button"
                      onClick={() => setAvatarFile(null)}
                      className="text-xs text-destructive hover:underline"
                    >
                      Remove
                    </button>
                  )}
                  <p className="text-xs text-muted-foreground">Click to upload photo</p>
                </div>
              </div>

              <div className="space-y-2 md:col-span-1">
                <Label>Full Name</Label>
                <Input value={fullName} onChange={e => setFullName(e.target.value)} required />
              </div>

              <div className="space-y-2 md:col-span-1">
                <Label>Date of Birth</Label>
                <Input type="date" value={dob} onChange={e => setDob(e.target.value)} />
              </div>

              <div className="space-y-2 md:col-span-1">
                <Label>Joining Date</Label>
                <Input type="date" value={joiningDate} onChange={e => setJoiningDate(e.target.value)} />
              </div>

              <div className="space-y-2 md:col-span-1">
                <Label>Email</Label>
                <Input type="email" value={email} onChange={e => setEmail(e.target.value)} />
              </div>

              <div className="space-y-2 md:col-span-1">
                <Label>Phone Number</Label>
                <Input value={phone} onChange={e => setPhone(e.target.value)} placeholder="+965 5xxxxxxx" />
              </div>

              <div className="space-y-2 md:col-span-1">
                <Label>Position</Label>
                <Input value={position} onChange={e => setPosition(e.target.value)} />
              </div>

              <div className="space-y-2 md:col-span-1">
                <Label>Nationality</Label>
                <Input value={nationality} onChange={e => setNationality(e.target.value)} />
              </div>

              <div className="space-y-2 md:col-span-1">
                <Label>Address</Label>
                <Input value={address} onChange={e => setAddress(e.target.value)} />
              </div>

              <div className="space-y-2 md:col-span-1">
                <Label>BioTime ID</Label>
                <Input value={zktecoId} onChange={e => setZktecoId(e.target.value)} placeholder="ID" />
              </div>

              {/* ── Branch → Department → Sub-Department → Manager cascade ── */}

              {/* Branch */}
              <div className="md:col-span-1">
                <Dropdown
                  label="Branch"
                  placeholder="Select branch…"
                  searchPlaceholder="Search branches…"
                  options={branchOptions}
                  value={branchId}
                  onChange={setBranchId}
                  clearable
                />
              </div>

              {/* Department */}
              <div className="md:col-span-1">
                <Dropdown
                  label={depsLoading ? "Department (loading…)" : "Department"}
                  placeholder="Select department…"
                  searchPlaceholder="Search departments…"
                  options={departmentOptions}
                  value={departmentId}
                  onChange={setDepartmentId}
                  disabled={!branchId || depsLoading}
                  clearable
                  emptyMessage={branchId ? "No departments for this branch." : "Select a branch first."}
                />
              </div>

              {/* Sub-Department */}
              <div className="md:col-span-1">
                <Dropdown
                  label={subDepsLoading ? "Sub Department (loading…)" : "Sub Department (if applicable)"}
                  placeholder="None"
                  searchPlaceholder="Search sub-departments…"
                  options={subDepartmentOptions}
                  value={subDepartmentId}
                  onChange={setSubDepartmentId}
                  disabled={!departmentId || subDepsLoading}
                  clearable
                  emptyMessage={departmentId ? "No sub-departments for this department." : "Select a department first."}
                />
              </div>

              {/* Reporting Manager */}
              <div className="md:col-span-1">
                <Dropdown
                  label={managersLoading ? "Reporting Manager (loading…)" : "Reporting Manager"}
                  placeholder="None"
                  searchPlaceholder="Search managers…"
                  options={managerOptions}
                  value={reportingManagerId}
                  onChange={setReportingManagerId}
                  clearable
                  emptyMessage="No managers found."
                />
              </div>
            </CardContent>
          </Card>

          {/* Shift */}
          <Card>
            <CardHeader><CardTitle className="text-sm font-medium">Shift Management</CardTitle></CardHeader>
            <CardContent className="grid gap-4 md:grid-cols-4">
              <div className="md:col-span-2">
                <Dropdown
                  label="Shift"
                  placeholder="Select shift…"
                  searchPlaceholder="Search shifts…"
                  options={shiftOptions}
                  value={shiftId}
                  onChange={setShiftId}
                  clearable
                  emptyMessage="No shifts available."
                />
              </div>
              <div className="space-y-2 md:col-span-2">
                <Label>Effective From</Label>
                <Input type="date" value={shiftEffectiveFrom} onChange={e => setShiftEffectiveFrom(e.target.value)} />
              </div>
            </CardContent>
          </Card>

          {/* Salary */}
          <Card>
            <CardHeader className="flex-row items-center justify-between">
              <CardTitle className="text-sm font-medium">Salary Breakdown</CardTitle>
              <Button type="button" variant="secondary" size="sm" onClick={addSalaryComponent}>Add Component</Button>
            </CardHeader>
            <CardContent className="space-y-4">
              {salaryComponents.map((s, idx) => (
                <div key={idx} className="grid gap-4 md:grid-cols-12">
                  <div className="space-y-2 md:col-span-7">
                    <Label>Category</Label>
                    <Input value={s.category} onChange={e => updateSalaryComponent(idx, { category: e.target.value })} placeholder="Base Salary" />
                  </div>
                  <div className="space-y-2 md:col-span-4">
                    <Label>Amount</Label>
                    <Input value={s.amount} onChange={e => updateSalaryComponent(idx, { amount: e.target.value })} type="number" min="0" step="0.001" />
                  </div>
                  <div className="flex items-end md:col-span-1">
                    <Button type="button" variant="ghost" size="sm" className="h-10" onClick={() => removeSalaryComponent(idx)} disabled={salaryComponents.length <= 1}>Remove</Button>
                  </div>
                </div>
              ))}
              <div className="grid grid-cols-2 gap-4 rounded-md border bg-muted/30 p-4 text-sm">
                <div className="font-medium">Total Payable</div>
                <div className="text-right font-semibold">{formatCurrency(totalPayable)}</div>
              </div>
            </CardContent>
          </Card>

          {/* Leave Allowances */}
          <Card>
            <CardHeader><CardTitle className="text-sm font-medium">Leave Allowances</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              {leaveAllowances.length === 0 && (
                <div className="rounded-md border bg-muted/30 p-3 text-sm text-muted-foreground">No leave types added.</div>
              )}
              <div className="space-y-3">
                {leaveAllowances.map((l, idx) => {
                  const isNew = !l.leaveTypeId
                  return (
                    <div key={idx} className="grid gap-3 rounded-md border p-3 md:grid-cols-12">
                      <div className="md:col-span-5">
                        <Dropdown
                          label="Leave Type"
                          placeholder="+ New leave type"
                          searchPlaceholder="Search leave types…"
                          options={leaveTypeOptions}
                          value={l.leaveTypeId}
                          onChange={(nextId) => updateLeaveAllowance(idx, { leaveTypeId: nextId, leaveTypeName: nextId ? "" : l.leaveTypeName })}
                          clearable
                          emptyMessage="No leave types found."
                        />
                      </div>
                      <div className="space-y-2 md:col-span-4">
                        <Label>{isNew ? "New Leave Type Name" : ""}</Label>
                        {isNew ? (
                          <Input value={l.leaveTypeName} onChange={e => updateLeaveAllowance(idx, { leaveTypeName: e.target.value })} placeholder="e.g., Maternity" />
                        ) : <div className="h-9" />}
                      </div>
                      <div className="space-y-2 md:col-span-2">
                        <Label>Days</Label>
                        <Input type="number" min={0} value={l.days} onChange={e => updateLeaveAllowance(idx, { days: e.target.value })} />
                      </div>
                      <div className="flex items-end justify-end md:col-span-1">
                        <Button type="button" variant="ghost" size="sm" onClick={() => removeLeaveAllowance(idx)}>Remove</Button>
                      </div>
                    </div>
                  )
                })}
              </div>
              <div className="flex justify-end">
                <Button type="button" variant="secondary" onClick={addLeaveAllowance}>Add Leave</Button>
              </div>
            </CardContent>
          </Card>

          {/* Login Account */}
          <Card>
            <CardHeader><CardTitle className="text-sm font-medium">Login Account</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <label className="flex items-center gap-2 text-sm">
                <input type="checkbox" className="h-4 w-4" checked={createUser} onChange={e => setCreateUser(e.target.checked)} disabled={hasUserAccount} />
                {hasUserAccount ? "Login account already created" : "Create login account for this employee"}
              </label>
              {createUser && (
                <div className="grid gap-4 md:grid-cols-2">
                  <div className="space-y-2">
                    <Label>Email (used for login)</Label>
                    <Input value={email} onChange={e => setEmail(e.target.value)} required={createUser} />
                  </div>
                  <div className="space-y-2">
                    <Label>{hasUserAccount ? "Reset Password (optional)" : "Password"}</Label>
                    <Input type="password" value={userPassword} onChange={e => setUserPassword(e.target.value)} placeholder="Set a temporary password" required={!hasUserAccount && createUser} />
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        </>
      )}

      {/* ══ TAB 2 — Documents ══ */}
      {tab === "Documents" && (
        <div className="space-y-6">
          <Card>
            <CardHeader><CardTitle className="text-sm font-medium">Civil ID</CardTitle></CardHeader>
            <CardContent className="grid gap-4 md:grid-cols-2">
              <div className="space-y-2">
                <Label>Civil ID Number <span className="text-muted-foreground text-xs">(optional)</span></Label>
                <Input value={civilId} onChange={e => setCivilId(e.target.value)} placeholder="e.g. 292030100001" />
              </div>
              <div className="space-y-2">
                <Label>Expiry Date <span className="text-muted-foreground text-xs">(optional)</span></Label>
                <Input type="date" value={civilIdExpiry} onChange={e => setCivilIdExpiry(e.target.value)} />
              </div>
              <div className="md:col-span-2">
                <FileUploadField label="Civil ID Copy" value={civilIdFile} onChange={setCivilIdFile} />
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader><CardTitle className="text-sm font-medium">Passport</CardTitle></CardHeader>
            <CardContent className="grid gap-4 md:grid-cols-2">
              <div className="space-y-2">
                <Label>Passport Number <span className="text-muted-foreground text-xs">(optional)</span></Label>
                <Input value={passportNumber} onChange={e => setPassportNumber(e.target.value)} />
              </div>
              <div className="space-y-2">
                <Label>Expiry Date <span className="text-muted-foreground text-xs">(optional)</span></Label>
                <Input type="date" value={passportExpiry} onChange={e => setPassportExpiry(e.target.value)} />
              </div>
              <div className="md:col-span-2">
                <FileUploadField label="Passport Copy" value={passportFile} onChange={setPassportFile} />
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader><CardTitle className="text-sm font-medium">Other Document</CardTitle></CardHeader>
            <CardContent>
              <FileUploadField label="Additional Document" value={otherFile} onChange={setOtherFile} />
            </CardContent>
          </Card>
        </div>
      )}
    </form>
  )
}