"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { ArrowLeft, Users, Mail } from "lucide-react";
import { useGetEmployee } from "../hooks/employee.hook";
import { useGetDepartments } from "@/modules/admin/departments/hooks/department.hook";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { employeeService } from "../services/employee.service";
import { EmployeeRole } from "../types/employee.type";
import { showToast } from "@/lib/toast";
import { capitalizeFirstLetter } from "@/lib/capitalize";

const ROLES: { value: EmployeeRole; label: string }[] = [
  { value: "EMPLOYEE", label: "Employee" },
  { value: "MANAGER", label: "Manager" },
];

const GENDERS = [
  { value: "MALE", label: "Male" },
  { value: "FEMALE", label: "Female" },
  { value: "OTHER", label: "Other" },
];

const EMP_STATUSES = [
  { value: "ACTIVE", label: "Active" },
  { value: "INVITED", label: "Invited" },
  { value: "SUSPENDED", label: "Suspended" },
  { value: "REVOKED", label: "Revoked" },
];

const FieldError = ({ msg }: { msg?: string }) =>
  msg ? <p className="mt-1 text-xs text-destructive">{msg}</p> : null;

export function EditEmployeePage({ id }: { id: string }) {
  const router = useRouter();
  const { data: emp, isLoading } = useGetEmployee(id);
  const { data: deptData } = useGetDepartments({ page: 1, limit: 100 });
  const departments = deptData?.data ?? [];
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [gender, setGender] = useState("");
  const [role, setRole] = useState<EmployeeRole>("EMPLOYEE");
  const [departmentId, setDepartmentId] = useState("");
  const [status, setStatus] = useState("");

  const qc = useQueryClient();
  const { mutate, isPending } = useMutation({
    mutationFn: (payload: {
      name: string;
      role: EmployeeRole;
      departmentId?: string;
      phone?: string;
      gender?: string;
      status?: string;
    }) => employeeService.updateEmployee(id, payload),
    onSuccess: (res: any) => {
      qc.invalidateQueries({ queryKey: ["employees"] });
      showToast.success(res.message || "Employee updated successfully!");
      router.push("/admin/employees");
    },
    onError: (err: any) => {
      showToast.error(
        err?.response?.data?.error || "Failed to update employee"
      );
    },
  });

  useEffect(() => {
    if (emp) {
      setName(emp.name ?? "");
      setRole(emp.role ?? "EMPLOYEE");
      setDepartmentId(emp.departmentId ?? emp.department?.id ?? "");
      setPhone(emp.phone ?? "");
      setGender(emp.gender ?? "");
      setStatus(emp.status ?? "ACTIVE");
    }
  }, [emp]);

  const handleSubmit = () => {
    const newErrors: Record<string, string> = {};
    if (!name.trim()) newErrors.name = "Full name is required";
    if (phone && !/^\+?[0-9]{7,15}$/.test(phone.replace(/\s/g, "")))
      newErrors.phone = "Enter a valid phone number";
    if (Object.keys(newErrors).length) {
      setErrors(newErrors);
      return;
    }
    setErrors({});
    mutate({
      name: capitalizeFirstLetter(name.trim()),
      role,
      status,
      ...(departmentId ? { departmentId } : {}),
      ...(phone.trim() ? { phone: phone.trim() } : { phone: "" }),
      ...(gender ? { gender } : { gender: "" }),
    });
  };

  const clearError = (key: string) =>
    setErrors((prev) => {
      const n = { ...prev };
      delete n[key];
      return n;
    });

  const initials = name
    .split(" ")
    .map((n) => n[0])
    .join("")
    .slice(0, 2)
    .toUpperCase();

  return (
    <div className="space-y-4">
      <button
        onClick={() => router.back()}
        className="text-muted-foreground hover:text-foreground flex items-center gap-1 text-sm"
      >
        <ArrowLeft className="h-4 w-4" /> Back
      </button>
      <div>
        <h2 className="text-2xl font-bold tracking-tight">Edit Employee</h2>
        <p className="text-muted-foreground text-sm mt-0.5">
          Update employee information
        </p>
      </div>

      {isLoading ? (
        <div className="flex flex-col md:flex-row gap-5 items-start w-full">
          <div className="flex flex-col gap-4">
            <Card>
              <CardContent className="p-6">
                <Skeleton className="h-40 w-64" />
              </CardContent>
            </Card>
            <Skeleton className="h-16 w-64 rounded-xl" />
          </div>
          <Card className="flex-1 w-full">
            <CardContent className="p-6 space-y-4">
              {[1, 2, 3, 4].map((i) => (
                <Skeleton key={i} className="h-10 w-full" />
              ))}
            </CardContent>
          </Card>
        </div>
      ) : (
        <div className="flex flex-col md:flex-row gap-5 items-start w-full">
          {/* LEFT */}
          <div className="flex flex-col gap-4">
            <Card>
              <CardContent className="p-6 flex flex-col items-center gap-3">
                <div className="w-20 h-20 rounded-xl bg-muted flex items-center justify-center">
                  {initials ? (
                    <span className="text-2xl font-bold text-primary">
                      {initials}
                    </span>
                  ) : (
                    <Users className="h-8 w-8 text-muted-foreground" />
                  )}
                </div>
                <div className="text-center">
                  <p className="text-sm font-semibold">{name || "Employee"}</p>
                  <p className="text-xs text-muted-foreground">
                    {emp?.email ?? "—"}
                  </p>
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="p-4 flex gap-3">
                <Mail className="h-4 w-4 text-muted-foreground mt-0.5 shrink-0" />
                <p className="text-xs text-muted-foreground leading-relaxed">
                  Email cannot be changed after invitation.
                </p>
              </CardContent>
            </Card>
          </div>

          {/* RIGHT */}
          <Card className="w-full">
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Users className="h-4 w-4 text-primary" /> Personal Information
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                    Full Name <span className="text-destructive">*</span>
                  </Label>
                  <Input
                    placeholder="e.g. Rahul Sharma"
                    value={name}
                    onChange={(e) => {
                      setName(e.target.value);
                      clearError("name");
                    }}
                    className={errors.name ? "border-destructive" : ""}
                  />
                  <FieldError msg={errors.name} />
                </div>

                <div className="space-y-1.5">
                  <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                    Email Address{" "}
                    <span className="text-xs normal-case font-normal">
                      (cannot be changed)
                    </span>
                  </Label>
                  <Input
                    type="email"
                    value={emp?.email ?? ""}
                    disabled
                    className="bg-muted text-muted-foreground cursor-not-allowed"
                  />
                </div>

                <div className="space-y-1.5">
                  <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                    Phone Number
                  </Label>
                  <Input
                    type="tel"
                    placeholder="e.g. +91 9876543210"
                    value={phone}
                    onChange={(e) => {
                      setPhone(e.target.value);
                      clearError("phone");
                    }}
                    className={errors.phone ? "border-destructive" : ""}
                  />
                  <FieldError msg={errors.phone} />
                </div>

                <div className="space-y-1.5">
                  <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                    Gender
                  </Label>
                  <Select value={gender} onValueChange={setGender}>
                    <SelectTrigger className="h-9 text-sm w-full">
                      <SelectValue placeholder="Select gender" />
                    </SelectTrigger>
                    <SelectContent>
                      {GENDERS.map((g) => (
                        <SelectItem key={g.value} value={g.value}>
                          {g.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-1.5">
                  <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                    Role <span className="text-destructive">*</span>
                  </Label>
                  <Select
                    value={role}
                    onValueChange={(v) => setRole(v as EmployeeRole)}
                  >
                    <SelectTrigger className="h-9 text-sm w-full">
                      <SelectValue placeholder="Select role" />
                    </SelectTrigger>
                    <SelectContent>
                      {ROLES.map((r) => (
                        <SelectItem key={r.value} value={r.value}>
                          {r.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-1.5">
                  <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                    Department
                  </Label>
                  <Select value={departmentId} onValueChange={setDepartmentId}>
                    <SelectTrigger className="h-9 text-sm w-full">
                      <SelectValue placeholder="Select department" />
                    </SelectTrigger>
                    <SelectContent>
                      {departments.map((d) => (
                        <SelectItem key={d.id} value={d.id}>
                          {d.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-1.5">
                  <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                    Status
                  </Label>
                  <Select value={status} onValueChange={setStatus}>
                    <SelectTrigger className="h-9 text-sm w-full">
                      <SelectValue placeholder="Select status" />
                    </SelectTrigger>
                    <SelectContent>
                      {EMP_STATUSES.map((s) => (
                        <SelectItem key={s.value} value={s.value}>
                          {s.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div className="flex items-center justify-end gap-3 mt-10 pt-4 border-t border-border">
                <Button
                  variant="ghost"
                  className="border border-border hover:bg-muted hover:text-foreground"
                  onClick={() => router.back()}
                >
                  Cancel
                </Button>
                <Button
                  type="button"
                  onClick={handleSubmit}
                  disabled={isPending}
                >
                  {isPending && (
                    <div className="w-4 h-4 border-2 border-primary-foreground border-t-transparent rounded-full animate-spin mr-2" />
                  )}
                  Save Changes
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      )}
    </div>
  );
}
