"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { Link2, Pencil, Plus, Users as UsersIcon } from "lucide-react"

import { employeesApi } from "@/lib/api/employees"
import { departmentsApi, designationsApi, employmentTypesApi, workShiftsApi } from "@/lib/api/hrm-masters"
import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { PaginationMeta } from "@/types/common"
import { CreateEmployeeRequest, Department, Designation, EmployeeListItem, EmploymentType, UserMatch, WorkShift } from "@/types/hrm"

import { Button, buttonVariants } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Skeleton } from "@/components/ui/skeleton"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { toast } from "@/components/ui/toast"

const PAGE_SIZE = 10

const emptyForm: CreateEmployeeRequest = {
  employeeCode: "",
  fullName: "",
  email: "",
  hireDate: new Date().toISOString().slice(0, 10),
  departmentId: 0,
  designationId: 0,
  employmentTypeId: 0,
  workShiftId: 0,
}

export default function EmployeesPage() {
  const [employees, setEmployees] = useState<EmployeeListItem[] | null>(null)
  const [pagination, setPagination] = useState<PaginationMeta | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [page, setPage] = useState(1)
  const [q, setQ] = useState("")

  const [departments, setDepartments] = useState<Department[]>([])
  const [designations, setDesignations] = useState<Designation[]>([])
  const [employmentTypes, setEmploymentTypes] = useState<EmploymentType[]>([])
  const [workShifts, setWorkShifts] = useState<WorkShift[]>([])

  const [open, setOpen] = useState(false)
  const [form, setForm] = useState<CreateEmployeeRequest>(emptyForm)
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [submitting, setSubmitting] = useState(false)

  // Advisory cross-link suggestion: does a System User already exist with this email?
  const [userMatch, setUserMatch] = useState<UserMatch | null>(null)
  const [checkingEmail, setCheckingEmail] = useState(false)

  function load() {
    employeesApi
      .list({ page, pageSize: PAGE_SIZE, q: q || undefined })
      .then((res) => { setEmployees(res.items); setPagination(res.pagination) })
      .catch((err) => setError(errorMessage(err)))
  }
  useEffect(load, [page, q])

  useEffect(() => {
    departmentsApi.list({ pageSize: 200, status: "Active" }).then((r) => setDepartments(r.items)).catch(() => setDepartments([]))
    designationsApi.list({ pageSize: 200, status: "Active" }).then((r) => setDesignations(r.items)).catch(() => setDesignations([]))
    employmentTypesApi.list({ pageSize: 200, status: "Active" }).then((r) => setEmploymentTypes(r.items)).catch(() => setEmploymentTypes([]))
    workShiftsApi.list({ pageSize: 200, status: "Active" }).then((r) => setWorkShifts(r.items)).catch(() => setWorkShifts([]))
  }, [])

  async function checkEmail(email: string) {
    if (!email.trim()) { setUserMatch(null); return }
    setCheckingEmail(true)
    try {
      const { match } = await employeesApi.emailLookup(email.trim())
      setUserMatch(match)
    } catch {
      setUserMatch(null)
    } finally {
      setCheckingEmail(false)
    }
  }

  function resetForm() {
    setForm(emptyForm)
    setUserMatch(null)
    setErrors({})
  }

  async function handleCreate() {
    const nextErrors: Record<string, string> = {}
    if (!form.employeeCode.trim()) nextErrors.employeeCode = "Employee code is required"
    if (!form.fullName.trim()) nextErrors.fullName = "Full name is required"
    if (!form.hireDate) nextErrors.hireDate = "Hire date is required"
    if (!form.departmentId) nextErrors.departmentId = "Department is required"
    if (!form.designationId) nextErrors.designationId = "Designation is required"
    if (!form.employmentTypeId) nextErrors.employmentTypeId = "Employment type is required"
    if (!form.workShiftId) nextErrors.workShiftId = "Work shift is required"
    setErrors(nextErrors)
    if (Object.keys(nextErrors).length > 0) return

    setSubmitting(true)
    try {
      await employeesApi.create({
        ...form,
        email: form.email || null,
        linkUserId: userMatch ? userMatch.userId : null,
      })
      toast.success("Employee created")
      setOpen(false)
      resetForm()
      load()
    } catch (err) {
      toast.error("Could not create employee", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="flex flex-col gap-6">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Employees</h1>
          <p className="text-base text-muted-foreground">Staff records — separate from system login accounts (see the link chip below).</p>
        </div>
        <Dialog open={open} onOpenChange={(v) => { setOpen(v); if (!v) resetForm() }}>
          <DialogTrigger render={<Button size="lg"><Plus className="size-5" />New Employee</Button>} />
          <DialogContent className="sm:max-w-lg">
            <DialogHeader className="items-center text-center">
              <DialogTitle>New Employee</DialogTitle>
              <DialogDescription>Not every employee needs a login — a system user account is optional and separate.</DialogDescription>
            </DialogHeader>
            <FieldGroup>
              <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                <Field data-invalid={!!errors.employeeCode}>
                  <FieldLabel htmlFor="e-code">Employee code</FieldLabel>
                  <Input id="e-code" value={form.employeeCode} onChange={(e) => setForm((f) => ({ ...f, employeeCode: e.target.value }))} aria-invalid={!!errors.employeeCode} />
                  <FieldError errors={[errors.employeeCode ? { message: errors.employeeCode } : undefined]} />
                </Field>
                <Field data-invalid={!!errors.hireDate}>
                  <FieldLabel htmlFor="e-hire">Hire date</FieldLabel>
                  <Input id="e-hire" type="date" value={form.hireDate} onChange={(e) => setForm((f) => ({ ...f, hireDate: e.target.value }))} aria-invalid={!!errors.hireDate} />
                  <FieldError errors={[errors.hireDate ? { message: errors.hireDate } : undefined]} />
                </Field>
              </div>
              <Field data-invalid={!!errors.fullName}>
                <FieldLabel htmlFor="e-name">Full name</FieldLabel>
                <Input id="e-name" value={form.fullName} onChange={(e) => setForm((f) => ({ ...f, fullName: e.target.value }))} aria-invalid={!!errors.fullName} />
                <FieldError errors={[errors.fullName ? { message: errors.fullName } : undefined]} />
              </Field>
              <Field>
                <FieldLabel htmlFor="e-email">Email (optional)</FieldLabel>
                <Input
                  id="e-email"
                  type="email"
                  value={form.email ?? ""}
                  onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))}
                  onBlur={(e) => checkEmail(e.target.value)}
                />
                {checkingEmail && <p className="text-sm text-muted-foreground">Checking for an existing system user…</p>}
                {userMatch && (
                  <div className="flex items-center gap-2 rounded-lg border border-primary/30 bg-primary/5 px-3 py-2 text-sm">
                    <Link2 className="size-4 shrink-0 text-primary" />
                    <span>
                      System user <strong>{userMatch.username}</strong> ({userMatch.displayName}) matches this email — it will be linked to this employee.
                    </span>
                  </div>
                )}
              </Field>
              <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                <Field data-invalid={!!errors.departmentId}>
                  <FieldLabel htmlFor="e-dept">Department</FieldLabel>
                  <Select value={form.departmentId ? String(form.departmentId) : undefined} onValueChange={(v) => setForm((f) => ({ ...f, departmentId: Number(v) }))}>
                    <SelectTrigger id="e-dept"><SelectValue placeholder="Select" /></SelectTrigger>
                    <SelectContent>{departments.map((d) => <SelectItem key={d.departmentId} value={String(d.departmentId)}>{d.name}</SelectItem>)}</SelectContent>
                  </Select>
                  <FieldError errors={[errors.departmentId ? { message: errors.departmentId } : undefined]} />
                </Field>
                <Field data-invalid={!!errors.designationId}>
                  <FieldLabel htmlFor="e-desig">Designation</FieldLabel>
                  <Select value={form.designationId ? String(form.designationId) : undefined} onValueChange={(v) => setForm((f) => ({ ...f, designationId: Number(v) }))}>
                    <SelectTrigger id="e-desig"><SelectValue placeholder="Select" /></SelectTrigger>
                    <SelectContent>{designations.map((d) => <SelectItem key={d.designationId} value={String(d.designationId)}>{d.name}</SelectItem>)}</SelectContent>
                  </Select>
                  <FieldError errors={[errors.designationId ? { message: errors.designationId } : undefined]} />
                </Field>
                <Field data-invalid={!!errors.employmentTypeId}>
                  <FieldLabel htmlFor="e-etype">Employment type</FieldLabel>
                  <Select value={form.employmentTypeId ? String(form.employmentTypeId) : undefined} onValueChange={(v) => setForm((f) => ({ ...f, employmentTypeId: Number(v) }))}>
                    <SelectTrigger id="e-etype"><SelectValue placeholder="Select" /></SelectTrigger>
                    <SelectContent>{employmentTypes.map((t) => <SelectItem key={t.employmentTypeId} value={String(t.employmentTypeId)}>{t.name}</SelectItem>)}</SelectContent>
                  </Select>
                  <FieldError errors={[errors.employmentTypeId ? { message: errors.employmentTypeId } : undefined]} />
                </Field>
                <Field data-invalid={!!errors.workShiftId}>
                  <FieldLabel htmlFor="e-shift">Work shift</FieldLabel>
                  <Select value={form.workShiftId ? String(form.workShiftId) : undefined} onValueChange={(v) => setForm((f) => ({ ...f, workShiftId: Number(v) }))}>
                    <SelectTrigger id="e-shift"><SelectValue placeholder="Select" /></SelectTrigger>
                    <SelectContent>{workShifts.map((w) => <SelectItem key={w.workShiftId} value={String(w.workShiftId)}>{w.name}</SelectItem>)}</SelectContent>
                  </Select>
                  <FieldError errors={[errors.workShiftId ? { message: errors.workShiftId } : undefined]} />
                </Field>
              </div>
            </FieldGroup>
            <div className="flex flex-col-reverse gap-3 pt-2 sm:flex-row sm:justify-center">
              <Button variant="outline" className="w-full sm:w-auto sm:min-w-32" onClick={() => setOpen(false)} disabled={submitting}>Cancel</Button>
              <Button className="w-full sm:w-auto sm:min-w-32" onClick={handleCreate} disabled={submitting}>{submitting ? "Creating…" : "Create"}</Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <Input placeholder="Search by name or employee code…" value={q} onChange={(e) => { setPage(1); setQ(e.target.value) }} className="max-w-sm" />

      {error && <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-5 text-base text-destructive">{error}</div>}

      {!error && employees === null && (
        <div className="flex flex-col gap-3">{Array.from({ length: 4 }).map((_, i) => <Skeleton key={i} className="h-14 w-full" />)}</div>
      )}

      {!error && employees !== null && employees.length === 0 && (
        <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed py-20 text-center">
          <UsersIcon className="size-12 text-muted-foreground" />
          <p className="text-base text-muted-foreground">No employees yet.</p>
        </div>
      )}

      {!error && employees !== null && employees.length > 0 && (
        <Table className="text-base">
          <TableHeader>
            <TableRow>
              <TableHead className="h-12 px-3 text-sm">Code</TableHead>
              <TableHead className="h-12 px-3 text-sm">Name</TableHead>
              <TableHead className="h-12 px-3 text-sm">Department</TableHead>
              <TableHead className="h-12 px-3 text-sm">Designation</TableHead>
              <TableHead className="h-12 px-3 text-sm">Login</TableHead>
              <TableHead className="h-12 px-3 text-sm">Status</TableHead>
              <TableHead className="h-12 px-3 text-sm">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {employees.map((e) => (
              <TableRow key={e.employeeId}>
                <TableCell className="px-3 py-3.5 font-medium">{e.employeeCode}</TableCell>
                <TableCell className="px-3 py-3.5">{e.fullName}</TableCell>
                <TableCell className="px-3 py-3.5">{e.departmentName ?? "—"}</TableCell>
                <TableCell className="px-3 py-3.5">{e.designationName ?? "—"}</TableCell>
                <TableCell className="px-3 py-3.5">
                  {e.hasUserLink ? (
                    <Badge variant="outline" className="h-6 w-fit justify-center gap-1 border-transparent bg-primary/10 px-2.5 text-sm text-primary"><Link2 className="size-3.5" />Linked</Badge>
                  ) : (
                    <span className="text-sm text-muted-foreground">No login</span>
                  )}
                </TableCell>
                <TableCell className="px-3 py-3.5">
                  <Badge variant="outline" className={cn("h-6 w-fit justify-center border-transparent px-2.5 text-sm", e.status === "Active" ? "bg-success/10 text-success" : "bg-muted text-muted-foreground")}>{e.status}</Badge>
                </TableCell>
                <TableCell className="px-3 py-3.5">
                  <Link href={`/dashboard/hrm/employees/${e.employeeId}`} className={cn(buttonVariants({ variant: "ghost", size: "icon-sm" }))} aria-label={`Edit ${e.fullName}`}>
                    <Pencil className="size-4" />
                  </Link>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}

      {pagination && pagination.totalPages > 1 && (
        <div className="flex items-center justify-between">
          <p className="text-sm text-muted-foreground">Showing {(pagination.page - 1) * pagination.pageSize + 1}–{Math.min(pagination.page * pagination.pageSize, pagination.totalItems)} of {pagination.totalItems}</p>
          <div className="flex items-center gap-2">
            <Button type="button" variant="outline" size="sm" disabled={pagination.page <= 1} onClick={() => setPage((p) => Math.max(1, p - 1))}>Previous</Button>
            <span className="text-sm text-muted-foreground">Page {pagination.page} of {pagination.totalPages}</span>
            <Button type="button" variant="outline" size="sm" disabled={pagination.page >= pagination.totalPages} onClick={() => setPage((p) => Math.min(pagination.totalPages, p + 1))}>Next</Button>
          </div>
        </div>
      )}
    </div>
  )
}
