"use client";

import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
import {
  ArrowLeft,
  BriefcaseBusiness,
  ChevronDown,
  Filter,
  MapPin,
  MoreHorizontal,
  Search,
  X,
} from "lucide-react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useMemo, useState } from "react";

type JobStatus = "active" | "inactive" | "completed";
type JobType = "Onsite" | "Remote";

type Job = {
  id: string;
  title: string;
  dept: string;
  position: number;
  tags: string[];
  experience: string;
  location: string;
  salary: string;
  status: JobStatus;
};

const SEED_JOBS: Job[] = [
  {
    id: "1",
    title: "UI/UX Designer",
    dept: "Design",
    position: 2,
    tags: ["Design", "Full Time", "Remote"],
    experience: "2 yrs Exp",
    location: "i8/3, Isb",
    salary: "75k/Month",
    status: "active",
  },
  {
    id: "2",
    title: "Sr. UX Researcher",
    dept: "Design",
    position: 2,
    tags: ["Design", "Full Time"],
    experience: "1 yrs Exp",
    location: "6th Road, Rwp",
    salary: "105k/Month",
    status: "active",
  },
  {
    id: "3",
    title: "BDM",
    dept: "Sales",
    position: 2,
    tags: ["Sales", "Full Time"],
    experience: "1 yrs Exp",
    location: "Saddar, Rwd",
    salary: "105k/Month",
    status: "active",
  },
  {
    id: "4",
    title: "HR Executive",
    dept: "HR",
    position: 2,
    tags: ["HR", "Full Time", "Remote"],
    experience: "",
    location: "Faizabad, Rwd",
    salary: "35k/Month",
    status: "inactive",
  },
  {
    id: "5",
    title: "Python Developer",
    dept: "Design",
    position: 2,
    tags: ["Developer", "Full Time"],
    experience: "",
    location: "Phase 8, Isb",
    salary: "105k/Month",
    status: "inactive",
  },
  {
    id: "6",
    title: "UI/UX Designer",
    dept: "Design",
    position: 2,
    tags: ["Design", "Full Time", "Remote"],
    experience: "",
    location: "4th Road, Rwd",
    salary: "65k/Month",
    status: "completed",
  },
  {
    id: "7",
    title: "Sr. UX Researcher",
    dept: "Design",
    position: 2,
    tags: ["Design", "Full Time"],
    experience: "",
    location: "7th Ave, Isb",
    salary: "115k/Month",
    status: "completed",
  },
  {
    id: "8",
    title: "BDM",
    dept: "BDM",
    position: 2,
    tags: ["Sales", "Full Time"],
    experience: "",
    location: "Saddar, Rwp",
    salary: "112k/Month",
    status: "completed",
  },
];

function StatusColumn({
  label,
  colorDot,
  panelClass,
  jobs,
  app,
}: {
  label: string;
  colorDot: string;
  panelClass: string;
  jobs: Job[];
  app: string;
}) {
  return (
    <div className={cn("rounded-lg border border-[#E8EDF2] p-3", panelClass)}>
      <div className="mb-2 flex items-center justify-between">
        <h3 className="text-[12px] font-semibold text-[#272833]">
          <span className={cn("mr-1.5 inline-block size-2 rounded-full", colorDot)} />
          {label}
        </h3>
      </div>

      <div className="space-y-2">
        {jobs.map((job) => (
          <Link
            key={job.id}
            href={`/${app}/jobs/${job.id}`}
            className="block rounded-md border border-[#E8EDF2] bg-white p-3 transition hover:bg-[#FAFBFD]"
          >
            <div className="mb-2 flex items-start justify-between gap-2">
              <div>
                <p className="text-[21px] font-semibold text-[#272833]">{job.title}</p>
                <p className="text-[12px] text-[#8B8D97]">{job.dept}</p>
              </div>
              <div className="text-right">
                <MoreHorizontal className="ml-auto size-4 text-[#A2AAB6]" />
                <p className="text-[11px] text-[#8B8D97]">Position: {job.position.toString().padStart(2, "0")}</p>
              </div>
            </div>

            <div className="mb-2 flex flex-wrap gap-1">
              {job.tags.map((tag) => (
                <span
                  key={tag}
                  className="inline-flex rounded bg-[#074473] px-2 py-0.5 text-[10px] font-semibold text-white"
                >
                  {tag}
                </span>
              ))}
            </div>

            <div className="flex items-center justify-between text-[11px] text-[#4B5563]">
              <div className="space-y-1">
                {job.experience ? (
                  <p className="inline-flex items-center gap-1">
                    <span className="inline-flex size-3.5 items-center justify-center rounded bg-[#111827] text-[9px] text-white">
                      E
                    </span>
                    {job.experience}
                  </p>
                ) : null}
                <p className="inline-flex items-center gap-1">
                  <MapPin className="size-3.5" />
                  {job.location}
                </p>
              </div>
              <p className="text-[28px] font-semibold text-[#272833]">{job.salary}</p>
            </div>
          </Link>
        ))}
      </div>
    </div>
  );
}

export default function Page() {
  const params = useParams<{ app: string }>();
  const app = params.app;
  const [rows, setRows] = useState<Job[]>(SEED_JOBS);
  const [openModal, setOpenModal] = useState(false);
  const [isActive, setIsActive] = useState(true);
  const [title, setTitle] = useState("");
  const [dept, setDept] = useState("");
  const [vacancies, setVacancies] = useState("2");
  const [location, setLocation] = useState("");
  const [exp, setExp] = useState("2");
  const [amount, setAmount] = useState("75000");
  const [desc, setDesc] = useState("");
  const [jobType, setJobType] = useState<JobType>("Onsite");
  const [fileName, setFileName] = useState("");
  const filePct = 42;

  const activeJobs = useMemo(() => rows.filter((r) => r.status === "active"), [rows]);
  const inactiveJobs = useMemo(() => rows.filter((r) => r.status === "inactive"), [rows]);
  const completedJobs = useMemo(() => rows.filter((r) => r.status === "completed"), [rows]);

  const addJob = () => {
    if (!title.trim()) return;
    const newJob: Job = {
      id: String(Date.now()),
      title: title.trim(),
      dept: dept || "Dev Department",
      position: Number(vacancies || 1),
      tags: [dept || "Design", "Full Time", jobType === "Remote" ? "Remote" : "Onsite"],
      experience: `${exp || 0} yrs Exp`,
      location: location || "i9/4, near gas station, Islamabad",
      salary: `${Math.round(Number(amount || 0) / 1000)}k/Month`,
      status: isActive ? "active" : "inactive",
    };
    setRows((prev) => [...prev, newJob]);
    setOpenModal(false);
  };

  return (
    <div className="space-y-4">
      <div className="mb-2 flex items-center justify-between gap-3">
        <div className="flex items-center gap-2.5">
          <Link href={`/${app}/dashboard`} className="rounded bg-white p-2 text-[#383E49]">
            <ArrowLeft className="size-4" />
          </Link>
          <h1 className="text-[30px] font-semibold leading-none text-[#272833]">All Jobs Posted</h1>
        </div>
        <Button
          className="h-9 rounded bg-[#074473] px-5 text-[12px] font-semibold text-white hover:bg-[#074473]/90"
          onClick={() => setOpenModal(true)}
        >
          Add New Job
        </Button>
      </div>

      <Card className="border-[#EBEEF2]">
        <CardContent className="space-y-3 p-4">
          <div className="flex items-center justify-between">
            <h2 className="text-[27px] font-semibold text-[#272833]">Jobs</h2>
            <div className="flex items-center gap-2">
              <div className="relative">
                <Search className="absolute left-2 top-1/2 size-3.5 -translate-y-1/2 text-[#9AA1AB]" />
                <Input className="h-8 w-[170px] bg-white pl-7 text-[11px]" placeholder="search" />
              </div>
              <Button variant="outline" className="h-8 gap-1 bg-white px-3 text-[11px]">
                <Filter className="size-3.5" /> Filters
              </Button>
            </div>
          </div>

          <div className="grid gap-3 lg:grid-cols-3">
            <StatusColumn label="Active Jobs" colorDot="bg-[#EAB308]" panelClass="bg-[#FFF8F1]" jobs={activeJobs} app={app} />
            <StatusColumn label="Inactive Jobs" colorDot="bg-[#F43F5E]" panelClass="bg-[#F8F7FF]" jobs={inactiveJobs} app={app} />
            <StatusColumn label="Completed Jobs" colorDot="bg-[#10B981]" panelClass="bg-[#F2FFF8]" jobs={completedJobs} app={app} />
          </div>
        </CardContent>
      </Card>

      {openModal ? (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/35 backdrop-blur-[2px] p-4">
          <div className="w-full max-w-[760px] rounded-xl bg-white p-5 shadow-2xl">
            <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]">
                <BriefcaseBusiness className="size-4" />
              </span>
              <div className="flex items-center gap-3">
                <div className="flex items-center gap-2">
                  <span className="text-[12px] text-[#545D69]">Status</span>
                  <Switch checked={isActive} onCheckedChange={setIsActive} />
                </div>
                <button type="button" onClick={() => setOpenModal(false)} className="inline-flex size-8 items-center justify-center rounded-lg bg-[#EEF5FB] text-[#5E6B7A]">
                  <X className="size-4" />
                </button>
              </div>
            </div>

            <h3 className="mb-3 text-[30px] font-semibold text-[#272833]">Add New Job</h3>

            <div className="grid gap-2.5 md:grid-cols-2">
              <Input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Enter Job Title" className="h-10 bg-[#F8F9FC] text-[12px]" />
              <label className="relative block">
                <Input value={dept} onChange={(e) => setDept(e.target.value)} placeholder="Select Department" className="h-10 bg-[#F8F9FC] pr-8 text-[12px]" />
                <ChevronDown className="absolute right-3 top-1/2 size-4 -translate-y-1/2 text-[#94A3B8]" />
              </label>
              <Input value={vacancies} onChange={(e) => setVacancies(e.target.value)} placeholder="No. of Vacancies" className="h-10 bg-[#F8F9FC] text-[12px]" />
              <label className="relative block">
                <Input value={location} onChange={(e) => setLocation(e.target.value)} placeholder="Select Location" className="h-10 bg-[#F8F9FC] pr-8 text-[12px]" />
                <MapPin className="absolute right-3 top-1/2 size-4 -translate-y-1/2 text-[#94A3B8]" />
              </label>
              <Input value={exp} onChange={(e) => setExp(e.target.value)} placeholder="Experience" className="h-10 bg-[#F8F9FC] text-[12px]" />
              <Input value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="Amount" className="h-10 bg-[#F8F9FC] text-[12px]" />
            </div>

            <Textarea rows={5} value={desc} onChange={(e) => setDesc(e.target.value)} placeholder="Job Description." className="mt-2.5 bg-[#F8F9FC] text-[12px]" />

            <div className="mt-2.5 flex items-center overflow-hidden rounded-md border border-[#D6DEE8] bg-white">
              <Input value={fileName} onChange={(e) => setFileName(e.target.value)} placeholder="Add Attachment" className="h-10 border-0 bg-transparent text-[12px]" />
              <button type="button" className="h-10 bg-[#B6CCE0] px-4 text-[12px] font-semibold text-white">Choose File</button>
            </div>
            {fileName ? (
              <div className="mt-1.5 rounded border border-[#D6DEE8] p-1.5">
                <p className="text-[10px] text-[#4B5563]">{fileName || "Dummy file"}</p>
                <div className="mt-1 h-1.5 rounded bg-[#E5E7EB]">
                  <div className="h-full rounded bg-[#074473]" style={{ width: `${filePct}%` }} />
                </div>
              </div>
            ) : null}

            <div className="mt-3">
              <p className="mb-1 text-[12px] text-[#545D69]">Select Type</p>
              <div className="flex items-center gap-5 text-[12px] text-[#6B7280]">
                <label className="inline-flex items-center gap-2"><input checked={jobType === "Onsite"} onChange={() => setJobType("Onsite")} type="radio" /> Onsite</label>
                <label className="inline-flex items-center gap-2"><input checked={jobType === "Remote"} onChange={() => setJobType("Remote")} type="radio" /> Remote Work</label>
              </div>
            </div>

            <div className="mt-4 flex items-center justify-center gap-3">
              <Button className="h-9 min-w-[110px] rounded bg-white text-[#111827]" variant="outline" onClick={() => setOpenModal(false)}>Cancel</Button>
              <Button className="h-9 min-w-[110px] rounded bg-[#074473] text-[12px] font-semibold text-white" onClick={addJob}>Add</Button>
            </div>
          </div>
        </div>
      ) : null}
    </div>
  );
}