// app/(dashboard)/client/post-job/page.tsx
"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { motion } from "framer-motion";
import {
  Briefcase,
  MapPin,
  Building2,
  Globe,
  ChevronRight,
  ChevronLeft,
  CheckCircle,
  X,
  FileText,
  Target,
  Sparkles,
  Layers
} from "lucide-react";
import { Card, CardContent } from "@/components/ui/Card";
import { Button } from "@/components/ui/Button";
import { Input } from "@/components/ui/Input";
import { Select } from "@/components/ui/Select";
import { Badge } from "@/components/ui/Badge";

export default function PostJobPage() {
  const router = useRouter();
  const [currentSection, setCurrentSection] = useState(1);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [skills, setSkills] = useState<string[]>([]);
  const [currentSkill, setCurrentSkill] = useState("");
  const [showPreview, setShowPreview] = useState(false);

  const jobSectors = [
    "Accounting & Finance", "Administration", "Agriculture", "Architecture", "Art & Design",
    "Automotive", "Banking", "Beauty & Spa", "Business Development", "Construction",
    "Consulting", "Customer Service", "Education", "Engineering", "Entertainment",
    "Farming", "Food & Beverage", "Healthcare", "Hospitality", "Human Resources",
    "Information Technology", "Insurance", "Legal", "Logistics", "Manufacturing",
    "Marketing", "Media & Communications", "Mining", "NGO", "Pharmaceutical",
    "Real Estate", "Retail", "Sales", "Science", "Security", "Social Services",
    "Sports & Fitness", "Supply Chain", "Telecommunications", "Tourism", "Transportation"
  ];

  const [formData, setFormData] = useState({
    title: "",
    jobSite: "onsite",
    jobSector: "",
    jobType: "fulltime",
    experienceLevel: "entry",
    educationQualification: "",
    genderPreference: "both",
    applicationDeadline: "",
    vacancies: "",
    description: "",
    country: "Ethiopia",
    city: "",
    workAddress: "",
    salaryType: "monthly",
    salaryAmount: "",
    salaryCurrency: "ETB"
  });

  const sections = [
    { id: 1, title: "Overview", icon: Briefcase, description: "Basic job info" },
    { id: 2, title: "Qualifications", icon: Target, description: "Experience & Education" },
    { id: 3, title: "Requirements", icon: FileText, description: "Skills & Description" },
    { id: 4, title: "Logistics", icon: MapPin, description: "Salary & Deadline" }
  ];

  const handleChange = (field: string, value: any) => {
    setFormData({ ...formData, [field]: value });
  };

  const addSkill = () => {
    if (currentSkill && !skills.includes(currentSkill)) {
      setSkills([...skills, currentSkill]);
      setCurrentSkill("");
    }
  };

  const removeSkill = (skill: string) => {
    setSkills(skills.filter(s => s !== skill));
  };

  const handleSubmit = async () => {
    setIsSubmitting(true);
    setTimeout(() => {
      setIsSubmitting(false);
      router.push("/client/jobs");
    }, 1500);
  };

  const containerVariants = {
    hidden: { opacity: 0, y: 10 },
    visible: { opacity: 1, y: 0, transition: { duration: 0.4 } }
  };

  

  const renderSectionContent = () => {
    switch (currentSection) {
      case 1:
        return (
          <motion.div key="sec1" variants={containerVariants} initial="hidden" animate="visible" className="space-y-8">
            <div className="space-y-2">
              <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">Job Title</label>
              <Input
                placeholder="e.g. Senior Backend Engineer"
                value={formData.title}
                onChange={(e) => handleChange("title", e.target.value)}
                className="py-8 px-6 text-lg font-black border-slate-100 focus:ring-sky-900 rounded-3xl"
              />
            </div>

            <div className="space-y-4">
              <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">Work Location Type</label>
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                {[
                  { value: "onsite", label: "On-site", icon: Building2, desc: "Office based" },
                  { value: "remote", label: "Remote", icon: Globe, desc: "Work from anywhere" },
                  { value: "hybrid", label: "Hybrid", icon: Layers, desc: "Mixed mode" }
                ].map(opt => (
                  <button
                    key={opt.value}
                    onClick={() => handleChange("jobSite", opt.value)}
                    className={`p-6 rounded-[2rem] border-2 text-left transition-all group ${formData.jobSite === opt.value ? "border-sky-900 bg-sky-50" : "border-slate-50 bg-white hover:border-sky-100"
                      }`}
                  >
                    <opt.icon className={`w-8 h-8 mb-4 ${formData.jobSite === opt.value ? "text-sky-900" : "text-slate-300"}`} />
                    <p className={`font-black text-sm ${formData.jobSite === opt.value ? "text-sky-900" : "text-slate-700"}`}>{opt.label}</p>
                    <p className="text-[10px] font-bold text-slate-400 uppercase mt-1">{opt.desc}</p>
                  </button>
                ))}
              </div>
            </div>

            <div className="space-y-2">
              <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">Job Sector</label>
              <Select
                options={jobSectors.map(s => ({ value: s, label: s }))}
                value={formData.jobSector}
                onChange={(e) => handleChange("jobSector", e.target.value)}
                placeholder="Select a category..."
                className="py-4 font-bold border-slate-100 rounded-3xl"
              />
            </div>
          </motion.div>
        );

      case 2:
        return (
          <motion.div key="sec2" variants={containerVariants} initial="hidden" animate="visible" className="space-y-8">
            <div className="space-y-4">
              <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">Employment Type</label>
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                {["Full-time", "Part-time", "Contract", "Freelance", "Internship", "Volunteer"].map(type => (
                  <button
                    key={type}
                    onClick={() => handleChange("jobType", type.toLowerCase())}
                    className={`py-4 rounded-2xl border-2 font-black text-xs uppercase tracking-tighter transition-all ${formData.jobType === type.toLowerCase() ? "border-sky-900 bg-sky-900 text-white" : "border-slate-50 bg-white text-slate-600 hover:border-sky-200"
                      }`}
                  >
                    {type}
                  </button>
                ))}
              </div>
            </div>

            <div className="space-y-4">
              <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">Experience Level</label>
              <div className="flex flex-wrap gap-3">
                {["Entry", "Junior", "Mid", "Senior", "Expert"].map(lvl => (
                  <button
                    key={lvl}
                    onClick={() => handleChange("experienceLevel", lvl.toLowerCase())}
                    className={`px-6 py-3 rounded-full border-2 font-black text-[10px] uppercase tracking-widest transition-all ${formData.experienceLevel === lvl.toLowerCase() ? "border-sky-900 bg-sky-900 text-white" : "border-slate-50 bg-white text-slate-500 hover:border-sky-200"
                      }`}
                  >
                    {lvl}
                  </button>
                ))}
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-2">
                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">Education Preference</label>
                <Select
                  options={[
                    { value: "any", label: "Any Education" },
                    { value: "bachelors", label: "Bachelor's Degree" },
                    { value: "masters", label: "Master's Degree" },
                    { value: "phd", label: "PhD" }
                  ]}
                  value={formData.educationQualification}
                  onChange={(e) => handleChange("educationQualification", e.target.value)}
                  className="font-bold border-slate-100 rounded-2xl"
                />
              </div>
              <div className="space-y-2">
                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">Gender Preference</label>
                <div className="flex gap-2">
                  {["Both", "Male", "Female"].map(g => (
                    <button
                      key={g}
                      onClick={() => handleChange("genderPreference", g.toLowerCase())}
                      className={`flex-1 py-3 rounded-2xl border-2 font-black text-[10px] uppercase transition-all ${formData.genderPreference === g.toLowerCase() ? "border-sky-900 bg-sky-50 text-sky-900" : "border-slate-50 text-slate-400"
                        }`}
                    >
                      {g}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          </motion.div>
        );

      case 3:
        return (
          <motion.div key="sec3" variants={containerVariants} initial="hidden" animate="visible" className="space-y-8">
            <div className="space-y-4">
              <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">Key Skills</label>
              <div className="flex gap-2">
                <Input
                  placeholder="e.g. React, Python, UI Design"
                  value={currentSkill}
                  onChange={(e) => setCurrentSkill(e.target.value)}
                  onKeyPress={(e) => e.key === "Enter" && addSkill()}
                  className="rounded-2xl border-slate-100 font-bold"
                />
                <Button variant="dark" onClick={addSkill} className="rounded-2xl px-6">Add</Button>
              </div>
              <div className="flex flex-wrap gap-2">
                {skills.map(s => (
                  <Badge key={s} className="bg-sky-50 text-sky-900 border-none font-black px-4 py-2 rounded-xl flex items-center gap-2">
                    {s}
                    <X className="w-3 h-3 cursor-pointer" onClick={() => removeSkill(s)} />
                  </Badge>
                ))}
              </div>
            </div>

            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">Job Description</label>
                <button onClick={() => setShowPreview(!showPreview)} className="text-[10px] font-black text-sky-600 uppercase tracking-widest hover:underline">
                  {showPreview ? "Hide Preview" : "Show Preview"}
                </button>
              </div>
              <textarea
                rows={10}
                placeholder="Describe the role in detail..."
                value={formData.description}
                onChange={(e) => handleChange("description", e.target.value)}
                className="w-full p-6 border-2 border-slate-50 rounded-[2rem] focus:outline-none focus:border-sky-900 font-medium text-slate-700 leading-relaxed transition-all"
              />
            </div>
          </motion.div>
        );

      case 4:
        return (
          <motion.div key="sec4" variants={containerVariants} initial="hidden" animate="visible" className="space-y-8">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
              <div className="space-y-4">
                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">Salary Details</label>
                <div className="flex gap-2">
                  <Input
                    placeholder="Amount"
                    type="number"
                    value={formData.salaryAmount}
                    onChange={(e) => handleChange("salaryAmount", e.target.value)}
                    className="flex-1 rounded-2xl border-slate-100 font-bold"
                  />
                  <Select
                    options={[{ value: "ETB", label: "ETB" }, { value: "USD", label: "USD" }]}
                    value={formData.salaryCurrency}
                    onChange={(e) => handleChange("salaryCurrency", e.target.value)}
                    className="w-24 rounded-2xl border-slate-100 font-bold"
                  />
                </div>
              </div>
              <div className="space-y-4">
                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">Application Deadline</label>
                <Input
                  type="date"
                  value={formData.applicationDeadline}
                  onChange={(e) => handleChange("applicationDeadline", e.target.value)}
                  className="rounded-2xl border-slate-100 font-bold"
                />
              </div>
            </div>

            <div className="space-y-4 p-8 bg-sky-50 rounded-[2.5rem] border border-sky-100 relative overflow-hidden group">
              <div className="absolute top-0 right-0 w-32 h-32 bg-sky-200/20 rounded-full -mr-16 -mt-16 blur-3xl transition-transform group-hover:scale-150 duration-700" />
              <div className="flex items-start gap-4 relative z-10">
                <div className="p-3 bg-white rounded-2xl shadow-sm">
                  <Sparkles className="w-5 h-5 text-sky-600" />
                </div>
                <div>
                  <h4 className="font-black text-sky-900 text-sm">Ready to post?</h4>
                  <p className="text-xs font-bold text-sky-600/70 mt-1 uppercase tracking-tighter">Review your details before going live to reach thousands of candidates.</p>
                </div>
              </div>
            </div>
          </motion.div>
        );
      default:
        return null;
    }
  };

  return (
    <div className="max-w-5xl mx-auto px-4 py-12 space-y-12 pb-32">
      {/* Horizontal Progress Header */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        {sections.map((section) => {
          const isActive = currentSection === section.id;
          const Icon = section.icon;
          const getCompletion = (id: number) => {
            switch (id) {
              case 1: return (formData.title && formData.jobSector) ? 100 : 50;
              case 2: return (formData.jobType && formData.experienceLevel) ? 100 : 50;
              case 3: return (skills.length > 0 && formData.description) ? 100 : 0;
              case 4: return (formData.salaryAmount && formData.applicationDeadline) ? 100 : 0;
              default: return 0;
            }
          };
          const completion = getCompletion(section.id);
          return (
            <button
              key={section.id}
              onClick={() => setCurrentSection(section.id)}
              className={`p-2 pr-6 rounded-full border-2 transition-all text-left relative group overflow-hidden flex items-center gap-4 ${isActive
                ? "border-sky-900 bg-sky-900 text-white shadow-xl shadow-sky-900/20 scale-[1.02]"
                : "border-slate-100 bg-white hover:border-sky-200"
                }`}
            >
              <div className={`p-4 rounded-full transition-colors ${isActive ? "bg-white/10" : "bg-slate-50 text-slate-400 group-hover:text-sky-500 shadow-sm"}`}>
                <Icon className="w-5 h-5" />
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center justify-between mb-0.5">
                  <h3 className={`font-black text-[10px] uppercase tracking-wider truncate ${isActive ? "text-white" : "text-slate-600"}`}>
                    {section.title}
                  </h3>
                  <div className={`text-[9px] font-black px-1.5 py-0.5 rounded-full ${completion === 100 ? (isActive ? "bg-emerald-400 text-sky-900" : "bg-emerald-100 text-emerald-600") : (isActive ? "bg-white/10 text-sky-300" : "bg-slate-100 text-slate-500")}`}>
                    {completion}%
                  </div>
                </div>
                <p className={`text-[9px] font-bold uppercase tracking-tighter truncate opacity-60 ${isActive ? "text-sky-100" : "text-slate-400"}`}>
                  {section.description}
                </p>
              </div>
              {isActive && (
                <motion.div layoutId="active-indicator" className="absolute bottom-0 left-0 right-0 h-1 bg-sky-400" />
              )}
            </button>
          );
        })}
      </div>

      {/* Main Form Card */}
      <Card className="border-slate-100/50 shadow-2xl shadow-slate-200/50 rounded-[2.5rem] overflow-hidden">
        <CardContent className="p-8 lg:p-12">
          {renderSectionContent()}

          {/* Navigation Buttons */}
          <div className="flex justify-between mt-12 pt-10 border-t-2 border-slate-50">
            {currentSection > 1 ? (
              <Button variant="outline" size="sm" onClick={() => setCurrentSection(currentSection - 1)} leftIcon={<ChevronLeft className="w-4 h-4" />}>
                Previous
              </Button>
            ) : (
              <div />
            )}

            <div className="flex items-center gap-3">
              {currentSection < 4 ? (
                <Button variant="dark" size="sm" onClick={() => setCurrentSection(currentSection + 1)} rightIcon={<ChevronRight className="w-4 h-4" />}>
                  Continue
                </Button>
              ) : (
                <Button
                  variant="dark"
                  size="sm"
                  onClick={handleSubmit}
                  loading={isSubmitting}
                  rightIcon={<CheckCircle className="w-4 h-4" />}
                  disabled={!formData.title || !formData.jobSector || skills.length === 0 || !formData.description || !formData.city}
                >
                  Post Job Now
                </Button>
              )}
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Review Summary Card */}
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        transition={{ delay: 0.5 }}
      >
        <Card variant="dark" className="border-none rounded-[2.5rem] shadow-xl shadow-sky-900/20 overflow-hidden relative">
          <div className="absolute top-0 right-0 w-64 h-64 bg-white/5 rounded-full -mr-32 -mt-32 blur-3xl pointer-events-none" />
          <CardContent className="p-8">
            <div className="flex items-center justify-between flex-wrap gap-8">
              <div className="flex items-center gap-5">
                <div className="p-4 bg-white/10 rounded-[1.5rem] shadow-inner backdrop-blur-sm">
                  <Sparkles className="w-6 h-6 text-sky-300" />
                </div>
                <div>
                  <p className="text-base font-black text-white tracking-tight">Draft Overview</p>
                  <p className="text-xs font-bold text-sky-300/60 uppercase tracking-[0.2em]">Review before you publish</p>
                </div>
              </div>
              <div className="flex gap-10 flex-wrap">
                <div className="space-y-1">
                  <p className="text-[10px] font-black text-sky-300/40 uppercase tracking-widest">Job Title</p>
                  <p className="text-sm font-bold text-white">{formData.title || "---"}</p>
                </div>
                <div className="space-y-1">
                  <p className="text-[10px] font-black text-sky-300/40 uppercase tracking-widest">Location</p>
                  <p className="text-sm font-bold text-white">{formData.city || "---"}</p>
                </div>
                <div className="space-y-1">
                  <p className="text-[10px] font-black text-sky-300/40 uppercase tracking-widest">Total Skills</p>
                  <p className="text-sm font-bold text-white">{skills.length} Required</p>
                </div>
              </div>
              <Button variant="outline" size="sm" className="border-white/20 text-white hover:bg-white hover:text-sky-900 px-8" onClick={() => setCurrentSection(1)}>
                Edit Draft
              </Button>
            </div>
          </CardContent>
        </Card>
      </motion.div>
    </div>
  );
}
