import React, { useState, useContext, useEffect } from 'react';
import axios from 'axios';
import { ApplicationContext } from '../context/ApplicationContext';

const Apply = () => {
  const { applications, setApplications } = useContext(ApplicationContext);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [credentials, setCredentials] = useState({ id: '', password: '' });
  const [formData, setFormData] = useState({
    positionName: '',
    qualification: '',
    experience: '',
    location: '',
    
    expertise: '',
    skills: [],
    numberOfOpenings: '',
    jobDescription: '',
    postingDate: new Date().toISOString().split('T')[0],
    isActive: true,
    closingDate: '',
  });
  const [showApplications, setShowApplications] = useState(false);
  const [editIndex, setEditIndex] = useState(null);
  const [searchTerm, setSearchTerm] = useState('');

  useEffect(() => {
    axios
      .get(`${process.env.REACT_APP_API_BASE_URL}/api/jobs`)
      .then((res) => {
        const currentDate = new Date();
        const updatedJobs = res.data.map(job => {
          if (job.closingDate && new Date(job.closingDate) < currentDate) {
            return { ...job, isActive: false };
          }
          return job;
        });
        setApplications(updatedJobs);
      })
      .catch((err) => console.error('Error fetching jobs:', err));
  }, [setApplications]);

  const handleLogin = (e) => {
    e.preventDefault();
    if (credentials.id === 'HR' && credentials.password === 'HR@#$2026') {
      setIsAuthenticated(true);
    } else {
      alert('Invalid credentials. Please try again.');
    }
  };

  const handleFormChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
      ...(name === 'positionName' ? { skills: [] } : {}),
    }));
  };

  const resetForm = () => {
    setFormData({
      positionName: '',
      qualification: '',
      experience: '',
      location: '',
      
      expertise: '',
      skills: [],
      numberOfOpenings: '',
      jobDescription: '',
      postingDate: new Date().toISOString().split('T')[0],
      isActive: true,
      closingDate: '',
    });
    setEditIndex(null);
  };

  const handleApplicationSubmit = (e) => {
    e.preventDefault();
    const currentDate = new Date();
    const closingDate = formData.closingDate ? new Date(formData.closingDate) : null;
    const isActive = closingDate ? closingDate >= currentDate : formData.isActive;

    const jobData = {
      ...formData,
      isActive
    };

    if (editIndex !== null) {
      const jobId = applications[editIndex].id;
      axios
        .put(`${process.env.REACT_APP_API_BASE_URL}/api/jobs/${jobId}`, jobData)
        .then((res) => {
          const updatedApps = [...applications];
          updatedApps[editIndex] = res.data.job;
          setApplications(updatedApps);
          resetForm();
        })
        .catch((err) => console.error('Error updating job:', err));
    } else {
      axios
        .post(`${process.env.REACT_APP_API_BASE_URL}/api/jobs`, jobData)
        .then((res) => {
          setApplications([...applications, res.data.job]);
          resetForm();
        })
        .catch((err) => console.error('Error creating job:', err));
    }
  };

  const handleDelete = (index) => {
    const jobId = applications[index].id;
    if (window.confirm('Are you sure you want to delete this job posting?')) {
      axios
        .delete(`${process.env.REACT_APP_API_BASE_URL}/api/jobs/${jobId}`)
        .then(() => {
          const updated = [...applications];
          updated.splice(index, 1);
          setApplications(updated);
        })
        .catch((err) => console.error('Error deleting job:', err));
    }
  };

  const handleEdit = (index) => {
    setEditIndex(index);
    setFormData(applications[index]);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const toggleActiveStatus = (index) => {
    const job = applications[index];
    const updatedJob = { ...job, isActive: !job.isActive };
    
    axios
      .put(`${process.env.REACT_APP_API_BASE_URL}/api/jobs/${job.id}`, updatedJob)
      .then((res) => {
        const updatedApps = [...applications];
        updatedApps[index] = res.data.job;
        setApplications(updatedApps);
      })
      .catch((err) => console.error('Error updating job status:', err));
  };

  const filteredApplications = applications.filter((app) =>
    app.positionName.toLowerCase().includes(searchTerm.toLowerCase()) ||
    app.location.toLowerCase().includes(searchTerm.toLowerCase()) ||
    (Array.isArray(app.skills) && app.skills.some((skill) => skill.toLowerCase().includes(searchTerm.toLowerCase())))
  );

  const handleLogout = () => {
    setIsAuthenticated(false);
    setCredentials({ id: '', password: '' });
    resetForm();
  };

  return (
    <div className="min-h-screen bg-gray-50 py-8 px-4 sm:px-6 lg:px-8">
      {!isAuthenticated ? (
        <div className="max-w-md mx-auto bg-white p-8 rounded-xl shadow-lg border border-gray-200">
          <div className="text-center mb-6">
            <h2 className="text-2xl font-bold text-gray-800">HR Portal Login</h2>
            <p className="text-gray-600 mt-2">Enter your credentials to access the job application system</p>
          </div>
          <form onSubmit={handleLogin} className="space-y-6">
            <div>
              <label htmlFor="id" className="block text-sm font-medium text-gray-700 mb-1">
                Username
              </label>
              <input
                id="id"
                type="text"
                placeholder="Username"
                autoComplete="off"
                className="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
                value={credentials.id}
                onChange={(e) => setCredentials({ ...credentials, id: e.target.value })}
                required
              />
            </div>
            <div>
              <label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-1">
                Password
              </label>
              <input
                id="password"
                type="password"
                placeholder="Password"
                autoComplete="new-password"
                className="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
                value={credentials.password}
                onChange={(e) => setCredentials({ ...credentials, password: e.target.value })}
                required
              />
            </div>
            <div>
              <button
                type="submit"
                className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700"
              >
                Sign in
              </button>
            </div>
          </form>
        </div>
      ) : (
        <div className="max-w-7xl mx-auto">
          <div className="flex justify-between items-center mb-8">
            <h1 className="text-3xl font-bold text-gray-900">Job Application Management</h1>
            <button
              onClick={handleLogout}
              className="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 transition-colors text-sm font-medium"
            >
              Logout
            </button>
          </div>

          {/* Job Form */}
          <div className="bg-white shadow-lg rounded-lg overflow-hidden mb-8">
            <div className="p-6 border-b border-gray-200">
              <h2 className="text-xl font-semibold text-gray-800">
                {editIndex !== null ? 'Edit Job Posting' : 'Create New Job Posting'}
              </h2>
            </div>
            <form onSubmit={handleApplicationSubmit} className="p-6 grid grid-cols-1 md:grid-cols-2 gap-6">

              {/* Position */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Position *</label>
                <input
                  type="text"
                  name="positionName"
                  placeholder="Enter position name"
                  className="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm"
                  value={formData.positionName}
                  onChange={handleFormChange}
                  required
                />
              </div>

              {/* Qualification */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Qualification *</label>
                <input
                  type="text"
                  name="qualification"
                  placeholder="e.g. Bachelor's Degree"
                  className="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm"
                  value={formData.qualification}
                  onChange={handleFormChange}
                  required
                />
              </div>

              {/* Experience */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Experience *</label>
                <input
                  type="text"
                  name="experience"
                  placeholder="e.g. 3-5 years"
                  className="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm"
                  value={formData.experience}
                  onChange={handleFormChange}
                  required
                />
              </div>

              {/* Location */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Location *</label>
                <input
                  type="text"
                  name="location"
                  placeholder="e.g. New York, NY"
                  className="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm"
                  value={formData.location}
                  onChange={handleFormChange}
                  required
                />
              </div>

              

              

              {/* Number of Openings */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Number of Openings *</label>
                <input
                  type="number"
                  name="numberOfOpenings"
                  placeholder="e.g. 2"
                  className="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm"
                  value={formData.numberOfOpenings}
                  onChange={handleFormChange}
                  required
                  min="1"
                />
              </div>

              {/* Posting Date */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Posting Date *</label>
                <input
                  type="date"
                  name="postingDate"
                  className="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm"
                  value={formData.postingDate}
                  onChange={handleFormChange}
                  required
                />
              </div>

              {/* Closing Date */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Closing Date (optional)</label>
                <input
                  type="date"
                  name="closingDate"
                  className="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm"
                  value={formData.closingDate}
                  onChange={handleFormChange}
                  min={formData.postingDate}
                />
                <p className="mt-1 text-xs text-gray-500">
                  If set, position will automatically deactivate after this date
                </p>
              </div>

              {/* Active Status */}
              <div className="flex items-center">
                <input
                  type="checkbox"
                  id="isActive"
                  name="isActive"
                  className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                  checked={formData.isActive}
                  onChange={(e) => setFormData({...formData, isActive: e.target.checked})}
                  disabled={!!formData.closingDate}
                />
                <label htmlFor="isActive" className="ml-2 block text-sm text-gray-700">
                  Active Position
                </label>
              </div>

              {/* Skills Multi-select */}
              <div className="md:col-span-2">
                <label className="block text-sm font-medium text-gray-700 mb-1">Required Skills *</label>
                <input
                  type="text"
                  name="skills"
                  placeholder="Enter skills separated by commas (e.g. AutoCAD, Billing, Teamwork)"
                  className="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm"
                  value={formData.skills.join(", ")}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      skills: e.target.value.split(",").map((s) => s.trim())
                    })
                  }
                />
                {formData.skills.length > 0 && (
                  <p className="mt-2 text-sm text-gray-500">
                    Selected: <span className="font-medium">{formData.skills.join(', ')}</span>
                  </p>
                )}
              </div>

              {/* Job Description */}
              <div className="md:col-span-2">
                <label className="block text-sm font-medium text-gray-700 mb-1">Job Description *</label>
                <textarea
                  name="jobDescription"
                  placeholder="Detailed description of the job..."
                  className="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm h-32"
                  value={formData.jobDescription}
                  onChange={handleFormChange}
                  required
                />
              </div>

              {/* Form Buttons */}
              <div className="md:col-span-2 flex justify-end space-x-3">
                {editIndex !== null && (
                  <button
                    type="button"
                    onClick={resetForm}
                    className="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white"
                  >
                    Cancel
                  </button>
                )}
                <button
                  type="submit"
                  className="px-4 py-2 border border-transparent rounded-md text-sm font-medium text-white bg-blue-600 hover:bg-blue-700"
                >
                  {editIndex !== null ? 'Update Job Posting' : 'Create Job Posting'}
                </button>
              </div>

            </form>
          </div>

          {/* Job Postings List */}
          {/* Keep the table as before, just remove Salary column if needed */}
        </div>
      )}
    </div>
  );
};

export default Apply;
