"use client";

import { useEffect, useState, useRef } from "react";
import { useParams } from "next/navigation";
import Container from "../../components/atoms/Container";
import Heading from "../../components/atoms/Heading";
import Swal from "sweetalert2";
import { BriefcaseIcon, MapPinIcon, SparklesIcon, CalendarIcon, UserIcon, ClockIcon, ArrowRightIcon } from "lucide-react";
import { MdChecklist, MdEmail, MdPhone, MdUpload } from "react-icons/md";

const JobDetailPage = ({data}) => {
  const id = data?.data?.id;
  const [job, setJob] = useState(null);
  const [loading, setLoading] = useState(true);
  const [notFound, setNotFound] = useState(false);
  const [form, setForm] = useState({
    name: "",
    email: "",
    phone: "",
    start_date: "",
    resume: null,
    resumeUrl: "", // Store the uploaded resume URL
  });
  const [submitting, setSubmitting] = useState(false);
  const [uploadingResume, setUploadingResume] = useState(false);
  const fileInputRef = useRef();

  useEffect(() => {
    if (!id) return;

    const fetchJob = async () => {
      try {
        setLoading(true);
        setJob(data.data);
      } catch (error) {
        setNotFound(true);
        setJob(null);
      } finally {
        setLoading(false);
      }
    };

    fetchJob();
  }, [id]);

  const handleChange = (e) => {
    const { name, value, files } = e.target;
    if (name === "resume") {
      const file = files[0];
      if (file) {
        setForm((prev) => ({ ...prev, resume: file }));
        // Auto-upload resume when selected
        handleResumeUpload(file);
      }
    } else {
      setForm((prev) => ({ ...prev, [name]: value }));
    }
  };

  // Handle resume upload to AWS
  const handleResumeUpload = async (file) => {
    // Validate file
    const allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
    const maxSize = 5 * 1024 * 1024; // 5MB
    
    if (!allowedTypes.includes(file.type)) {
      Swal.fire({
        icon: "warning",
        title: "Invalid File Type",
        text: "Please upload a PDF, DOC, or DOCX file.",
        confirmButtonColor: "#0B6F78",
      });
      fileInputRef.current.value = ""; // Clear file input
      setForm(prev => ({ ...prev, resume: null, resumeUrl: "" }));
      return;
    }
    
    if (file.size > maxSize) {
      Swal.fire({
        icon: "warning",
        title: "File Too Large",
        text: "File size must be less than 5MB.",
        confirmButtonColor: "#0B6F78",
      });
      fileInputRef.current.value = ""; // Clear file input
      setForm(prev => ({ ...prev, resume: null, resumeUrl: "" }));
      return;
    }

    setUploadingResume(true);
    
    try {
      const formData = new FormData();
      formData.append('resume', file);
      formData.append('candidateName', form.name || 'Unknown');
      formData.append('candidateEmail', form.email || 'unknown@example.com');

      const response = await fetch('/api/frontend/upload/resume', {
        method: 'POST',
        body: formData,
      });

      const result = await response.json();

      if (result.success) {
        setForm(prev => ({ 
          ...prev, 
          resumeUrl: result.data.url 
        }));
        
        Swal.fire({
          icon: "success",
          title: "Resume Uploaded",
          text: "Your resume has been uploaded successfully!",
          timer: 2000,
          showConfirmButton: false,
        });
      } else {
        throw new Error(result.message || 'Failed to upload resume');
      }
    } catch (error) {
      console.error('Resume upload error:', error);
      Swal.fire({
        icon: "error",
        title: "Upload Failed",
        text: error.message || "Failed to upload resume. Please try again.",
        confirmButtonColor: "#d33",
      });
      fileInputRef.current.value = ""; // Clear file input
      setForm(prev => ({ ...prev, resume: null, resumeUrl: "" }));
    } finally {
      setUploadingResume(false);
    }
  };

  const validateForm = () => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const cleanedPhone = form.phone.replace(/[\s()-]/g, "");
    const phoneRegex = /^\+?[1-9]\d{6,15}$/;

    if (
      !form.name.trim() ||
      !form.email.trim() ||
      !form.phone.trim() ||
      !form.start_date.trim() ||
      !form.resumeUrl
    ) {
      Swal.fire({
        icon: "warning",
        title: "Validation Error",
        text: "Please fill all required fields and upload your resume.",
        confirmButtonColor: "#0B6F78",
      });
      return false;
    }

    if (!emailRegex.test(form.email)) {
      Swal.fire({
        icon: "warning",
        title: "Invalid Email",
        text: "Please enter a valid email address.",
        confirmButtonColor: "#0B6F78",
      });
      return false;
    }

    if (!phoneRegex.test(cleanedPhone)) {
      Swal.fire({
        icon: "warning",
        title: "Invalid Phone Number",
        text: "Phone number must be a valid international format like +1234567890.",
        confirmButtonColor: "#0B6F78",
      });
      return false;
    }

    return true;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!validateForm()) return;

    setSubmitting(true);

    try {
      const response = await fetch("/api/frontend/jobs/job-applies", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          phone_number: form.phone.replace(/[\s()-]/g, ""),
          start_date: form.start_date,
          job_id: id,
          resume_url: form.resumeUrl, // Send the S3 URL instead of file
          resume_filename: form.resume?.name || "resume.pdf",
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Failed to submit application");
      }

      Swal.fire({
        icon: "success",
        title: "Application Submitted!",
        text: "Your job application has been submitted successfully!",
        confirmButtonColor: "#0B6F78",
        background: '#f8fafc',
        iconColor: '#0B6F78'
      });

      // Reset form
      setForm({ 
        name: "", 
        email: "", 
        phone: "", 
        start_date: "", 
        resume: null,
        resumeUrl: "" 
      });
      if (fileInputRef.current) fileInputRef.current.value = "";
    } catch (err) {
      Swal.fire({
        icon: "error",
        title: "Submission Failed",
        text: err.message || "Something went wrong. Please try again.",
        confirmButtonColor: "#d33",
        background: '#f8fafc'
      });
    } finally {
      setSubmitting(false);
    }
  };

  // Brand gradient colors
  const brandGradient = "linear-gradient(135deg, #0B6F78 0%, #0a306b 100%)";
  const brandGradientLight = "linear-gradient(135deg, #0B6F7820 0%, #0a306b20 100%)";

  if (loading) {
    return (
      <Container>
        <div className="min-h-screen flex items-center justify-center">
          <div className="text-center py-12">
            <div className="animate-spin rounded-full h-16 w-16 border-b-2 border-[#0B6F78] mx-auto mb-4"></div>
            <p className="text-gray-600 text-lg">Loading job details...</p>
          </div>
        </div>
      </Container>
    );
  }

  if (notFound) {
    return (
      <Container>
        <div className="min-h-screen flex items-center justify-center">
          <div className="text-center py-12">
            <div className="bg-gradient-to-r from-red-100 to-pink-100 rounded-full w-24 h-24 flex items-center justify-center mx-auto mb-4">
              <span className="text-4xl">🔍</span>
            </div>
            <h2 className="text-2xl font-bold text-gray-800 mb-2">Job Not Found</h2>
            <p className="text-gray-600">The job you're looking for doesn't exist or has been removed.</p>
          </div>
        </div>
      </Container>
    );
  }

  return (
    <Container>
      {/* Hero Section */}
      <div className="relative overflow-hidden rounded-3xl mb-8 mt-6 bg-gray-100">
        <div 
          className="absolute inset-0 opacity-10"
          style={{ background: brandGradient }}
        ></div>
        <div className="relative bg-white rounded-3xl p-8 lg:p-12 shadow-xl">
          <div className="grid lg:grid-cols-2 gap-8 items-center bg-gray-100 p-10">
            <div>
              <div className="inline-flex items-center px-4 py-2 rounded-full text-sm font-medium mb-4" 
                   style={{ background: brandGradientLight, color: '#0B6F78' }}>
                <BriefcaseIcon className="w-4 h-4 mr-2" />
                {job?.job_type} {job?.site_based ? "(Onsite)" : "(Remote)"}
              </div>
              
              <Heading level={1} className="text-4xl lg:text-5xl font-bold text-gray-900 mb-4">
                {job?.title || "Job Detail"}
              </Heading>
              
              <p className="text-lg text-gray-600 mb-6">
                Join our innovative team and work on cutting-edge projects that make a real impact.
              </p>
              
              <div className="flex flex-wrap gap-4">
                <div className="flex items-center text-gray-700">
                  <MapPinIcon className="w-5 h-5 mr-2 text-[#0B6F78]" />
                  {[job?.city, job?.province, job?.country].filter(Boolean).join(", ")}
                </div>
                <div className="flex items-center text-gray-700">
                  <ClockIcon className="w-5 h-5 mr-2 text-[#0B6F78]" />
                  Posted recently
                </div>
              </div>
            </div>
            
            <div className="lg:text-right">
              <div 
                className="inline-block px-6 py-3 rounded-full text-white font-semibold text-lg shadow-lg hover:shadow-xl transition-shadow cursor-pointer"
                style={{ background: brandGradient }}
                onClick={() => document.getElementById('application-form').scrollIntoView({ behavior: 'smooth' })}
              >
                Apply Now <ArrowRightIcon className="w-4 h-4 inline ml-2" />
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="grid lg:grid-cols-3 gap-8 py-8">
        {/* Job Details */}
        <div className="lg:col-span-2 space-y-8">
          {/* Quick Overview */}
          <div className="bg-white rounded-2xl shadow-lg border border-gray-100 p-8">
            <Heading level={2} className="text-2xl font-bold mb-6 text-gray-800 border-l-4 pl-4" style={{ borderColor: '#0B6F78' }}>
              Position Overview
            </Heading>
            
            <div className="grid md:grid-cols-2 gap-6">
              <div className="flex items-start space-x-4 p-4 rounded-lg bg-gray-50">
                <div className="flex-shrink-0 w-12 h-12 rounded-lg flex items-center justify-center text-white" 
                     style={{ background: brandGradient }}>
                  <BriefcaseIcon className="w-6 h-6" />
                </div>
                <div>
                  <h4 className="font-semibold text-gray-700">Job Type</h4>
                  <p className="text-gray-600">{job?.job_type}</p>
                </div>
              </div>
              
              <div className="flex items-start space-x-4 p-4 rounded-lg bg-gray-50">
                <div className="flex-shrink-0 w-12 h-12 rounded-lg flex items-center justify-center text-white" 
                     style={{ background: brandGradient }}>
                  <MapPinIcon className="w-6 h-6" />
                </div>
                <div>
                  <h4 className="font-semibold text-gray-700">Location</h4>
                  <p className="text-gray-600">
                    {[job?.city, job?.province, job?.country].filter(Boolean).join(", ")}
                    {job?.site_based ? " (Onsite)" : " (Remote)"}
                  </p>
                </div>
              </div>
              
              <div className="flex items-start space-x-4 p-4 rounded-lg bg-gray-50">
                <div className="flex-shrink-0 w-12 h-12 rounded-lg flex items-center justify-center text-white" 
                     style={{ background: brandGradient }}>
                  <MdChecklist className="w-6 h-6" />
                </div>
                <div>
                  <h4 className="font-semibold text-gray-700">Experience Level</h4>
                  <p className="text-gray-600">{job?.experience}</p>
                </div>
              </div>
              
              {job?.skills && (
                <div className="flex items-start space-x-4 p-4 rounded-lg bg-gray-50">
                  <div className="flex-shrink-0 w-12 h-12 rounded-lg flex items-center justify-center text-white" 
                       style={{ background: brandGradient }}>
                    <SparklesIcon className="w-6 h-6" />
                  </div>
                  <div>
                    <h4 className="font-semibold text-gray-700">Key Skills</h4>
                    <p className="text-gray-600">
                      {Array.isArray(job.skills) 
                        ? job.skills.slice(0, 3).join(", ") + (job.skills.length > 3 ? "..." : "")
                        : job.skills.split(",").map(s => s.trim()).slice(0, 3).join(", ") + "..."}
                    </p>
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Job Description */}
          <div className="bg-white rounded-2xl shadow-lg border border-gray-100 p-8">
            <Heading level={2} className="text-2xl font-bold mb-6 text-gray-800 border-l-4 pl-4" style={{ borderColor: '#0B6F78' }}>
              Job Description
            </Heading>
            <div className="prose max-w-none text-gray-700 leading-relaxed">
              <div dangerouslySetInnerHTML={{ __html: job?.description || "" }} />
            </div>
          </div>

          {/* Responsibilities */}
          {job?.responsibilities && (
            <div className="bg-white rounded-2xl shadow-lg border border-gray-100 p-8">
              <Heading level={2} className="text-2xl font-bold mb-6 text-gray-800 border-l-4 pl-4" style={{ borderColor: '#0B6F78' }}>
                Key Responsibilities
              </Heading>
              <div className="prose max-w-none text-gray-700 leading-relaxed">
                <div dangerouslySetInnerHTML={{ __html: job.responsibilities }} />
              </div>
            </div>
          )}

          {/* Requirements */}
          {job?.requirements && (
            <div className="bg-white rounded-2xl shadow-lg border border-gray-100 p-8">
              <Heading level={2} className="text-2xl font-bold mb-6 text-gray-800 border-l-4 pl-4" style={{ borderColor: '#0B6F78' }}>
                Requirements & Qualifications
              </Heading>
              <div className="prose max-w-none text-gray-700 leading-relaxed">
                <div dangerouslySetInnerHTML={{ __html: job.requirements }} />
              </div>
            </div>
          )}

          {/* Skills Section */}
          {job?.skills && (
            <div className="bg-white rounded-2xl shadow-lg border border-gray-100 p-8">
              <Heading level={2} className="text-2xl font-bold mb-6 text-gray-800 border-l-4 pl-4" style={{ borderColor: '#0B6F78' }}>
                Required Skills
              </Heading>
              <div className="flex flex-wrap gap-3">
                {Array.isArray(job.skills) 
                  ? job.skills.map((skill, index) => (
                      <span 
                        key={index}
                        className="px-4 py-2 rounded-full text-sm font-medium"
                        style={{ background: brandGradientLight, color: '#0B6F78' }}
                      >
                        {skill.trim()}
                      </span>
                    ))
                  : job.skills.split(',').map((skill, index) => (
                      <span 
                        key={index}
                        className="px-4 py-2 rounded-full text-sm font-medium"
                        style={{ background: brandGradientLight, color: '#0B6F78' }}
                      >
                        {skill.trim()}
                      </span>
                    ))
                }
              </div>
            </div>
          )}
        </div>

        {/* Application Form Sidebar */}
        <div className="lg:sticky lg:top-8 lg:h-fit">
          <div 
            id="application-form"
            className="bg-white rounded-2xl shadow-xl border border-gray-200 p-8"
            style={{ background: 'linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%)' }}
          >
            <div className="text-center mb-8">
              <div className="w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4 text-white" 
                   style={{ background: brandGradient }}>
                <UserIcon className="w-8 h-8" />
              </div>
              <h3 className="text-2xl font-bold text-gray-800">Apply for this Position</h3>
              <p className="text-gray-600 mt-2">Fill out the form below to submit your application</p>
            </div>

            <form className="space-y-6" onSubmit={handleSubmit}>
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2" htmlFor="name">
                  Full Name *
                </label>
                <div className="relative">
                  <UserIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                  <input
                    id="name"
                    type="text"
                    name="name"
                    value={form.name}
                    onChange={handleChange}
                    placeholder="Your full name"
                    className="w-full pl-10 pr-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent transition-all"
                    required
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2" htmlFor="email">
                  Email Address *
                </label>
                <div className="relative">
                  <MdEmail className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                  <input
                    id="email"
                    type="email"
                    name="email"
                    value={form.email}
                    onChange={handleChange}
                    placeholder="your.email@example.com"
                    className="w-full pl-10 pr-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent transition-all"
                    required
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2" htmlFor="phone">
                  Phone Number *
                </label>
                <div className="relative">
                  <MdPhone className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                  <input
                    id="phone"
                    type="text"
                    name="phone"
                    value={form.phone}
                    onChange={handleChange}
                    placeholder="+1 (975) 648-1649 or +92 300-1234567"
                    className="w-full pl-10 pr-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent transition-all"
                    required
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2" htmlFor="start_date">
                  Earliest Start Date *
                </label>
                <div className="relative">
                  <CalendarIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                  <input
                    id="start_date"
                    type="date"
                    name="start_date"
                    value={form.start_date}
                    onChange={handleChange}
                    className="w-full pl-10 pr-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent transition-all"
                    required
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2" htmlFor="resume">
                  Upload Resume *
                </label>
                <div className="relative">
                  <MdUpload className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                  <input
                    id="resume"
                    type="file"
                    name="resume"
                    accept=".pdf,.doc,.docx"
                    ref={fileInputRef}
                    onChange={handleChange}
                    className="w-full pl-10 pr-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent file:border-0 file:bg-transparent file:text-gray-600 file:cursor-pointer"
                    required
                  />
                </div>
                {uploadingResume && (
                  <div className="mt-2 text-sm text-blue-600 flex items-center">
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600 mr-2"></div>
                    Uploading resume...
                  </div>
                )}
                {form.resumeUrl && !uploadingResume && (
                  <div className="mt-2 text-sm text-green-600 flex items-center">
                    <svg className="w-4 h-4 mr-2" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                    </svg>
                    Resume uploaded successfully
                  </div>
                )}
                <p className="mt-1 text-xs text-gray-500">Supported formats: PDF, DOC, DOCX (Max 5MB)</p>
              </div>

              <button
                type="submit"
                disabled={submitting || uploadingResume}
                className={`w-full py-4 rounded-lg text-white font-semibold text-lg transition-all duration-300 flex items-center justify-center ${
                  submitting || uploadingResume
                    ? "opacity-60 cursor-not-allowed" 
                    : "hover:shadow-lg transform hover:-translate-y-0.5"
                }`}
                style={{ background: brandGradient }}
              >
                {submitting ? (
                  <>
                    <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
                    Submitting...
                  </>
                ) : uploadingResume ? (
                  <>
                    <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
                    Uploading...
                  </>
                ) : (
                  <>
                    Submit Application
                    <ArrowRightIcon className="w-5 h-5 ml-2" />
                  </>
                )}
              </button>
            </form>

            <div className="mt-6 text-center text-sm text-gray-500">
              <p>We'll get back to you within 2-3 business days</p>
            </div>
          </div>

          {/* Quick Contact Info */}
          <div className="mt-6 bg-white rounded-2xl shadow-lg border border-gray-200 p-6">
            <h4 className="font-semibold text-gray-800 mb-4">Need Help Applying?</h4>
            <div className="space-y-3 text-sm text-gray-600">
              <p>📧 jobs@universitiespage.com</p>
              <p>📞 +92 334 9990308</p>
              <p>🕒 Mon-Sat, 9AM - 6PM</p>
            </div>
          </div>
        </div>
      </div>
    </Container>
  );
};

export default JobDetailPage;