"use client"

import { useState, useEffect } from "react"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Search, Plus, Trash2 } from "lucide-react"
import { Avatar, AvatarFallback, AvatarImage } from "./ui/avatar"

type Employee = {
  id: string
  employeeNum?: string
  name: string
  username: string
  department: string
  position: string
  selfieImage?: string
  status: "Active" | "Inactive"
}

export function EmployeeTable() {
  const [searchTerm, setSearchTerm] = useState("")
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)
  const [newEmployee, setNewEmployee] = useState({
    name: "",
    username: "",
    department: "",
    position: "",
    status: "Active" as const,
  })
  const [employees, setEmployees] = useState<Employee[]>([])

  // Fetch employees from backend instead of localStorage
  useEffect(() => {
    const fetchEmployees = async () => {
      try {
      const res = await fetch("/api/employees")
      if (!res.ok) {
        throw new Error("Failed to fetch employees")
      }
      const data = await res.json()
      // Expecting data to have a `users` property with an array of employees
      setEmployees(data.users || [])
      } catch (error) {
        console.error("Error fetching employees:", error)
        setEmployees([])
      }
    }

    fetchEmployees()
  }, [])

  const filteredEmployees = employees.filter(
    (employee) =>
      employee.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      employee.id.toLowerCase().includes(searchTerm.toLowerCase()) ||
      employee.department.toLowerCase().includes(searchTerm.toLowerCase()) ||
      employee.position.toLowerCase().includes(searchTerm.toLowerCase())
  )

  const handleAddEmployee = () => {
    const newId = `EMP${String(employees.length + 1).padStart(3, "0")}`
    const newEmployeeWithId = {
      ...newEmployee,
      id: newId,
      // Generate a simple password (in a real app, this would be more secure)
      password: `${newEmployee.username}123`,
    }

    // For demonstration, we add the new employee to local state.
    // In a real app, you would post this data to an API endpoint.
    setEmployees([...employees, newEmployeeWithId])
    setNewEmployee({ name: "", username: "", department: "", position: "", status: "Active" })
    setIsAddDialogOpen(false)
  }

  const handleDeleteEmployee = (id: string) => {
    setEmployees(employees.filter((emp) => emp.id !== id))
  }

  const handleToggleStatus = (id: string) => {
    setEmployees(
      employees.map((emp) =>
        emp.id === id ? { ...emp, status: emp.status === "Active" ? "Inactive" : "Active" } : emp
      )
    )
  }

  return (
    <div className="bg-white dark:bg-slate-800 rounded-lg shadow">
      <div className="p-6">
        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
          <h2 className="text-xl font-semibold">Employee Directory</h2>
          <div className="flex gap-4 w-full sm:w-auto">
            <div className="relative flex-1 sm:flex-initial">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-slate-400" />
              <Input
                placeholder="Search employees..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-9 w-full sm:w-64"
              />
            </div>
            <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
              <DialogTrigger asChild>
                <Button className="flex items-center gap-2">
                  <Plus className="h-4 w-4" />
                  Add Employee
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>Add New Employee</DialogTitle>
                  <DialogDescription>Add a new employee to the system.</DialogDescription>
                </DialogHeader>
                <div className="space-y-4 py-4">
                  <div className="space-y-2">
                    <Label htmlFor="name">Full Name</Label>
                    <Input
                      id="name"
                      value={newEmployee.name}
                      onChange={(e) => setNewEmployee({ ...newEmployee, name: e.target.value })}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="username">Username</Label>
                    <Input
                      id="username"
                      value={newEmployee.username}
                      onChange={(e) => setNewEmployee({ ...newEmployee, username: e.target.value })}
                    />
                    <p className="text-xs text-slate-500">
                      Password will be automatically set to:{" "}
                      {newEmployee.username ? `${newEmployee.username}123` : "username123"}
                    </p>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="department">Department</Label>
                    <Select
                      value={newEmployee.department}
                      onValueChange={(value) => setNewEmployee({ ...newEmployee, department: value })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select department" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="Special Project">Special Project</SelectItem>
                        <SelectItem value="ICT">ICT</SelectItem>
                        <SelectItem value="Civil Infrastructure">Civil Infrastructure</SelectItem>
                        <SelectItem value="Admin">Admin</SelectItem>
                        <SelectItem value="HR">HR</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="position">Position</Label>
                    <Input
                      id="position"
                      value={newEmployee.position}
                      onChange={(e) => setNewEmployee({ ...newEmployee, position: e.target.value })}
                    />
                  </div>
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setIsAddDialogOpen(false)}>
                    Cancel
                  </Button>
                  <Button
                    onClick={handleAddEmployee}
                    disabled={
                      !newEmployee.name || !newEmployee.username || !newEmployee.department || !newEmployee.position
                    }
                  >
                    Add Employee
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b dark:border-slate-700">
                <th className="text-left py-3 px-4 font-medium">ID</th>
                <th className="text-left py-3 px-4 font-medium">EmployeeId</th>
                <th className="text-left py-3 px-4 font-medium">Name</th>
                <th className="text-left py-3 px-4 font-medium">Username</th>
                <th className="text-left py-3 px-4 font-medium">Department</th>
                <th className="text-left py-3 px-4 font-medium">Position</th>
                <th className="text-left py-3 px-4 font-medium">Profile</th>
                <th className="text-left py-3 px-4 font-medium">Status</th>
                <th className="text-right py-3 px-4 font-medium">Actions</th>
              </tr>
            </thead>
            <tbody>
              {filteredEmployees.length > 0 ? (
                filteredEmployees.map((employee) => (
                  <tr key={employee.id} className="border-b dark:border-slate-700">
                    <td className="py-3 px-4">{employee.id}</td>
                    <td className="py-3 px-4">{employee.employeeNum}</td>
                    <td className="py-3 px-4">{employee.name}</td>
                    <td className="py-3 px-4">{employee.username}</td>
                    <td className="py-3 px-4">{employee.department}</td>
                    <td className="py-3 px-4">{employee.position}</td>
                    <td className="py-3 px-4">
  <Avatar className="h-12 w-12">
    {employee.selfieImage ? (
      <AvatarImage
        src={`data:image/jpeg;base64,${employee.selfieImage}`}
        alt={`${employee.name}'s profile`}
        loading="lazy"
        onError={(e) => {
          // fallback to initials if image fails to load
          (e.target as HTMLImageElement).style.display = "none"
        }}
      />
    ) : null}
    <AvatarFallback className="text-sm font-medium">
      {employee.name
        .split(" ")
        .map((n) => n[0])
        .join("")
        .toUpperCase()}
    </AvatarFallback>
  </Avatar>
</td>

                    <td className="py-3 px-4">
                      <Badge
                        variant={employee.status === "Active" ? "default" : "secondary"}
                        className={`cursor-pointer ${
                          employee.status === "Active"
                            ? "bg-green-100 text-green-800 hover:bg-green-200 dark:bg-green-900/20 dark:text-green-400"
                            : "bg-red-100 text-red-800 hover:bg-red-200 dark:bg-red-900/20 dark:text-red-400"
                        }`}
                        onClick={() => handleToggleStatus(employee.id)}
                      >
                        {employee.status}
                      </Badge>
                    </td>
                    <td className="py-3 px-4 text-right">
                      <Button
                        variant="ghost"
                        size="sm"
                        className="text-red-500 hover:text-red-600"
                        onClick={() => handleDeleteEmployee(employee.id)}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={9} className="py-6 text-center text-slate-500 dark:text-slate-400">
                    No employees found.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}