"use client";

import placeHolderImage from "@/assets/images/avatar.jpeg";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
import { Briefcase, ChevronRight, Pencil, Trash2, X } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { useMemo, useState } from "react";

type Department = {
  id: string;
  name: string;
  members: number;
};

const SEED_DEPARTMENTS: Department[] = [
  { id: "design", name: "Design", members: 20 },
  { id: "sales", name: "Sales", members: 19 },
  { id: "manager", name: "Project Manager", members: 10 },
  { id: "marketing", name: "Marketing", members: 15 },
];

const EMPLOYEES = [
  { name: "Diane Russel", role: "Lead UI/UX Designer" },
  { name: "Jerome McCoy", role: "Lead UI/UX Designer" },
  { name: "Cathy Fisher", role: "Lead UI/UX Designer" },
  { name: "Cameron Wills", role: "Lead UI/UX Designer" },
  { name: "Ronald Richards", role: "Lead UI/UX Designer" },
];

function ModalShell({
  open,
  onClose,
  children,
  width = "max-w-[500px]",
}: {
  open: boolean;
  onClose: () => void;
  children: React.ReactNode;
  width?: string;
}) {
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/35 backdrop-blur-[2px] p-4">
      <div className={cn("w-full rounded-xl bg-white p-5 shadow-2xl", width)}>
        <div className="mb-4 flex items-start justify-between">
          <span className="inline-flex size-10 items-center justify-center rounded-lg border border-[#E7ECF2] text-[#0B1727]">
            <Briefcase className="size-4" />
          </span>
          <button
            type="button"
            onClick={onClose}
            className="inline-flex size-8 items-center justify-center rounded-lg bg-[#EEF5FB] text-[#5E6B7A]"
          >
            <X className="size-4" />
          </button>
        </div>
        {children}
      </div>
    </div>
  );
}

export default function Page({ params }: { params: { app: string } }) {
  const { app } = params;
  const [departments, setDepartments] = useState<Department[]>(SEED_DEPARTMENTS);
  const [openAdd, setOpenAdd] = useState(false);
  const [openEdit, setOpenEdit] = useState(false);
  const [openDelete, setOpenDelete] = useState(false);
  const [formName, setFormName] = useState("");
  const [activeDepartment, setActiveDepartment] = useState<Department | null>(null);

  const heading = useMemo(
    () => (
      <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <h1 className="text-[32px] font-semibold leading-none text-[#272833]">All Departments Information</h1>
        <Button
          className="h-9 rounded bg-[#074473] px-5 text-[12px] font-semibold text-white hover:bg-[#074473]/90"
          onClick={() => {
            setFormName("");
            setOpenAdd(true);
          }}
        >
          Add New Department
        </Button>
      </div>
    ),
    [],
  );

  return (
    <div className="space-y-4">
      {heading}

      <div className="grid gap-4 md:grid-cols-2">
        {departments.map((department) => (
          <Card key={department.id} className="border-[#EBEEF2]">
            <CardContent className="space-y-4 p-5">
              <div className="flex items-center justify-between border-b border-[#EBEEF2] pb-3">
                <div>
                  <h2 className="text-[28px] font-semibold text-[#272833]">{department.name} Department</h2>
                  <p className="text-[13px] text-[#8B8D97]">{department.members} Members</p>
                </div>

                <div className="flex items-center gap-2">
                  <button
                    type="button"
                    onClick={() => {
                      setActiveDepartment(department);
                      setFormName(`${department.name} Deprtment`);
                      setOpenEdit(true);
                    }}
                    className="inline-flex size-7 items-center justify-center rounded bg-[#EEF5FB] text-[#074473]"
                    aria-label={`Edit ${department.name}`}
                  >
                    <Pencil className="size-3.5" />
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      setActiveDepartment(department);
                      setOpenDelete(true);
                    }}
                    className="inline-flex size-7 items-center justify-center rounded bg-[#FEECEC] text-[#F04438]"
                    aria-label={`Delete ${department.name}`}
                  >
                    <Trash2 className="size-3.5" />
                  </button>
                  <Link href={`/${app}/departments/${department.id}`} className="text-[12px] font-semibold text-[#074473]">
                    View All
                  </Link>
                </div>
              </div>

              <div className="space-y-3">
                {EMPLOYEES.slice(0, 5).map((employee) => (
                  <div key={`${department.id}-${employee.name}`} className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <Image src={placeHolderImage} className="size-10 rounded-full object-cover" alt={employee.name} />
                      <div>
                        <p className="text-[13px] font-medium text-[#272833]">{employee.name}</p>
                        <p className="text-[11px] text-[#8B8D97]">{employee.role}</p>
                      </div>
                    </div>
                    <ChevronRight className="size-4 text-[#A4ABB4]" />
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      <ModalShell open={openAdd} onClose={() => setOpenAdd(false)} width="max-w-[520px]">
        <h3 className="mb-3 text-[30px] font-semibold text-[#272833]">Add New Department</h3>
        <p className="mb-1 text-[12px] text-[#545D69]">Name Of Department</p>
        <Input
          value={formName}
          onChange={(e) => setFormName(e.target.value)}
          className="mb-4 h-11 rounded-md border border-[#EEF1F4] bg-[#F8F9FC] text-[14px]"
          placeholder="Name Of Department"
        />
        <div className="flex items-center justify-center gap-3">
          <Button className="h-9 min-w-[110px] rounded bg-[#F79009] text-[12px] font-semibold text-white" onClick={() => setOpenAdd(false)}>
            Cancel
          </Button>
          <Button
            className="h-9 min-w-[110px] rounded bg-[#074473] text-[12px] font-semibold text-white"
            onClick={() => {
              if (!formName.trim()) return;
              const id = formName.toLowerCase().replace(/\s+/g, "-");
              setDepartments((prev) => [...prev, { id, name: formName.trim(), members: 0 }]);
              setOpenAdd(false);
            }}
          >
            Add
          </Button>
        </div>
      </ModalShell>

      <ModalShell open={openEdit} onClose={() => setOpenEdit(false)} width="max-w-[520px]">
        <h3 className="mb-3 text-[30px] font-semibold text-[#272833]">Add New Department</h3>
        <p className="mb-1 text-[12px] text-[#545D69]">Name Of Department</p>
        <Input
          value={formName}
          onChange={(e) => setFormName(e.target.value)}
          className="mb-4 h-11 rounded-md border border-[#EEF1F4] bg-[#F8F9FC] text-[14px]"
          placeholder="Name Of Department"
        />
        <div className="flex items-center justify-center gap-3">
          <Button className="h-9 min-w-[110px] rounded bg-[#F79009] text-[12px] font-semibold text-white" onClick={() => setOpenEdit(false)}>
            Cancel
          </Button>
          <Button
            className="h-9 min-w-[110px] rounded bg-[#074473] text-[12px] font-semibold text-white"
            onClick={() => {
              if (!activeDepartment || !formName.trim()) return;
              setDepartments((prev) => prev.map((d) => (d.id === activeDepartment.id ? { ...d, name: formName.trim() } : d)));
              setOpenEdit(false);
            }}
          >
            Add
          </Button>
        </div>
      </ModalShell>

      <ModalShell open={openDelete} onClose={() => setOpenDelete(false)} width="max-w-[560px]">
        <h3 className="mb-4 text-[30px] font-semibold text-[#272833]">Delete Department</h3>
        <p className="mb-5 text-center text-[31px] font-semibold leading-tight text-[#272833]">
          Are You Sure You Want To Delete
          <br />
          {activeDepartment?.name ?? "Design"} Department?
        </p>
        <div className="flex items-center justify-center gap-3">
          <Button className="h-9 min-w-[110px] rounded bg-[#F79009] text-[12px] font-semibold text-white" onClick={() => setOpenDelete(false)}>
            Cancel
          </Button>
          <Button
            className="h-9 min-w-[110px] rounded bg-[#074473] text-[12px] font-semibold text-white"
            onClick={() => {
              if (!activeDepartment) return;
              setDepartments((prev) => prev.filter((d) => d.id !== activeDepartment.id));
              setOpenDelete(false);
            }}
          >
            Delete
          </Button>
        </div>
      </ModalShell>
    </div>
  );
}