"use client";

import { useState, useEffect } from "react";
import { useParams, useRouter } from "next/navigation";
import { ArrowLeft, Save, Upload, Calendar as CalendarIcon, Plus, Trash2 } from "lucide-react";
import Swal from 'sweetalert2';
import Image from "next/image";
import dynamic from 'next/dynamic';

const SummernoteEditor = dynamic(() => import('../../../components/organisms/SummernoteEditor'), { 
  ssr: false,
  loading: () => <p className="p-4 bg-gray-100 rounded-lg">Loading editor...</p>
});

const EditScholarship = () => {
  const router = useRouter();
  const params = useParams();
  const id = params.id;
  
  const [formData, setFormData] = useState({
    title: "",
    slug: "",
    country_id: "",
    qualification_ids: [],
    image: "",
    deadline: "",
    description: "",
    cgpa: "",
    percentage_cover: "",
    amount_min: "", // Changed from amount to amount_min
    amount_max: "", // Added amount_max
    ielts: "",
    is_active: true,
    faqs: [{ question: "", answer: "" }]
  });

  const [countries, setCountries] = useState([]);
  const [qualifications, setQualifications] = useState([]);
  const [loading, setLoading] = useState(false);
  const [fetching, setFetching] = useState(true);
  const [uploading, setUploading] = useState(false);
  const [imagePreview, setImagePreview] = useState(null);

  useEffect(() => {
    if (id) {
      fetchScholarshipData();
      fetchDropdownData();
    }
  }, [id]);

  // Generate slug from title when editing title (optional)
  useEffect(() => {
    if (formData.title && !formData.slug) {
      const generatedSlug = formData.title
        .toLowerCase()
        .replace(/[^a-z0-9 -]/g, '')
        .replace(/\s+/g, '-')
        .replace(/-+/g, '-')
        .trim();
      
      setFormData(prev => ({
        ...prev,
        slug: generatedSlug
      }));
    }
  }, [formData.title]);

  const fetchScholarshipData = async () => {
    try {
      const res = await fetch(`/api/internal/scholarships?id=${id}`, { method: "PATCH"});
      if (!res.ok) throw new Error("Failed to fetch scholarship");
      
      const data = await res.json();
      
      console.log('Scholarship data:', data);
      
      if (data.success && data.data) {
        const scholarship = data.data;
        
        // Set basic form data with amount range
        const formDataUpdate = {
          title: scholarship.title || "",
          slug: scholarship.slug || "",
          country_id: scholarship.country_id || "",
          qualification_ids: scholarship.qualifications ? scholarship.qualifications.map(q => q.qualification_id.toString()) : [],
          image: scholarship.image || "",
          deadline: scholarship.deadline ? scholarship.deadline.split('T')[0] : "",
          description: scholarship.description || "",
          cgpa: scholarship.cgpa || "",
          percentage_cover: scholarship.percentage_cover || "",
          amount_min: scholarship.amount_min || "", // Set amount_min
          amount_max: scholarship.amount_max || "", // Set amount_max
          ielts: scholarship.ielts !== undefined && scholarship.ielts !== null 
            ? scholarship.ielts.toString() 
            : "",
          is_active: scholarship.is_active !== 0,
          faqs: scholarship.faqs && scholarship.faqs.length > 0 
            ? scholarship.faqs.map(faq => ({ question: faq.question, answer: faq.answer }))
            : [{ question: "", answer: "" }]
        };
        
        setFormData(formDataUpdate);
        
        if (scholarship.image) {
          setImagePreview(`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${scholarship.image}`);
        }
      } else {
        throw new Error(data.error || "Failed to load scholarship data");
      }
    } catch (error) {
      console.error('Error fetching scholarship:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: error.message || 'Failed to load scholarship data',
      });
    } finally {
      setFetching(false);
    }
  };

  const fetchDropdownData = async () => {
    try {
      // Fetch countries
      const countriesRes = await fetch('/api/internal/country', { method: "POST" });
      const countriesData = await countriesRes.json();
      setCountries(countriesData.data || []);

      // Fetch qualifications
      const qualificationsRes = await fetch('/api/internal/new/getpostlevel', { method: "POST" });
      const qualificationsData = await qualificationsRes.json();
      setQualifications(qualificationsData.data || []);
    } catch (error) {
      console.error('Error fetching dropdown data:', error);
    }
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSelectChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  // Handle multiple qualification selection
  const handleQualificationChange = (e) => {
    const selectedOptions = Array.from(e.target.selectedOptions, option => option.value);
    setFormData(prev => ({
      ...prev,
      qualification_ids: selectedOptions
    }));
  };

  // Handle FAQ changes
  const handleFaqChange = (index, field, value) => {
    const updatedFaqs = [...formData.faqs];
    updatedFaqs[index][field] = value;
    setFormData(prev => ({
      ...prev,
      faqs: updatedFaqs
    }));
  };

  // Add new FAQ
  const addFaq = () => {
    setFormData(prev => ({
      ...prev,
      faqs: [...prev.faqs, { question: "", answer: "" }]
    }));
  };

  // Remove FAQ
  const removeFaq = (index) => {
    if (formData.faqs.length > 1) {
      const updatedFaqs = formData.faqs.filter((_, i) => i !== index);
      setFormData(prev => ({
        ...prev,
        faqs: updatedFaqs
      }));
    }
  };

  const handleCheckboxChange = (e) => {
    const { name, checked } = e.target;
    console.log(`Checkbox ${name} changed to:`, checked);
    setFormData(prev => ({
      ...prev,
      [name]: checked
    }));
  };

  const handleDescriptionChange = (content) => {
    setFormData(prev => ({
      ...prev,
      description: content
    }));
  };

  const handleImageChange = async (e) => {
    const file = e.target.files?.[0];
    if (file) {
      if (file.size > 2 * 1024 * 1024) {
        Swal.fire({
          icon: 'warning',
          title: 'File Too Large',
          text: 'Image size should be less than 2MB.',
          confirmButtonColor: '#0B6D76',
        });
        return;
      }

      if (!file.type.startsWith('image/')) {
        Swal.fire({
          icon: 'error',
          title: 'Invalid File',
          text: 'Please select an image file.',
          confirmButtonColor: '#0B6D76',
        });
        return;
      }

      try {
        setUploading(true);
        const uploadFormData = new FormData();
        uploadFormData.append('image', file);
        uploadFormData.append('uploadType', 'scholarships');

        const uploadResponse = await fetch('/api/internal/upload', {
          method: 'POST',
          body: uploadFormData,
        });

        const uploadResult = await uploadResponse.json();

        if (!uploadResponse.ok) {
          throw new Error(uploadResult.message || 'Upload failed');
        }

        setFormData(prev => ({ ...prev, image: uploadResult.s3Key }));
        setImagePreview(uploadResult.url);
        
        Swal.fire({
          icon: 'success',
          title: 'Image Uploaded!',
          text: 'Image has been uploaded successfully.',
          confirmButtonColor: '#0B6D76',
          timer: 2000,
          showConfirmButton: false
        });
      } catch (error) {
        console.error('Upload error:', error);
        Swal.fire({
          icon: 'error',
          title: 'Upload Failed',
          text: `Upload failed: ${error.message}`,
          confirmButtonColor: '#0B6D76',
        });
      } finally {
        setUploading(false);
      }
    }
  };

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

    console.log('🔄 Form submission started with data:', formData);

    // Validation
    if (!formData.title || !formData.slug || !formData.deadline) {
      Swal.fire({
        icon: 'error',
        title: 'Missing Fields',
        text: 'Please fill in all required fields.',
        confirmButtonColor: '#0B6D76',
      });
      return;
    }

    // Validate qualifications
    if (!formData.qualification_ids || formData.qualification_ids.length === 0) {
      Swal.fire({
        icon: 'error',
        title: 'Missing Qualifications',
        text: 'Please select at least one qualification.',
        confirmButtonColor: '#0B6D76',
      });
      return;
    }

    // Validate FAQs
    const hasEmptyFaqs = formData.faqs.some(faq => !faq.question.trim() || !faq.answer.trim());
    if (hasEmptyFaqs) {
      Swal.fire({
        icon: 'error',
        title: 'Incomplete FAQs',
        text: 'Please fill in all FAQ questions and answers.',
        confirmButtonColor: '#0B6D76',
      });
      return;
    }

    // Validate CGPA if provided
    if (formData.cgpa && (formData.cgpa < 0 || formData.cgpa > 4)) {
      Swal.fire({
        icon: 'error',
        title: 'Invalid CGPA',
        text: 'CGPA must be between 0 and 4.',
        confirmButtonColor: '#0B6D76',
      });
      return;
    }

    // Validate percentage cover if provided
    if (formData.percentage_cover && (formData.percentage_cover < 0 || formData.percentage_cover > 100)) {
      Swal.fire({
        icon: 'error',
        title: 'Invalid Percentage',
        text: 'Percentage cover must be between 0 and 100.',
        confirmButtonColor: '#0B6D76',
      });
      return;
    }

    // Validate amount range if both are provided
    if (formData.amount_min && formData.amount_max) {
      const min = parseFloat(formData.amount_min);
      const max = parseFloat(formData.amount_max);
      if (min > max) {
        Swal.fire({
          icon: 'error',
          title: 'Invalid Amount Range',
          text: 'Minimum amount cannot be greater than maximum amount.',
          confirmButtonColor: '#0B6D76',
        });
        return;
      }
    }

    try {
      setLoading(true);
      
      // Prepare the data for submission with proper data types
      const submitData = {
        title: formData.title,
        slug: formData.slug,
        country_id: formData.country_id || null,
        qualification_ids: formData.qualification_ids,
        faqs: formData.faqs,
        image: formData.image || null,
        deadline: formData.deadline,
        description: formData.description || null,
        cgpa: formData.cgpa || null,
        percentage_cover: formData.percentage_cover || null,
        amount_min: formData.amount_min || null, // Send amount_min
        amount_max: formData.amount_max || null, // Send amount_max
        ielts: formData.ielts === "1" ? 1 : (formData.ielts === "0" ? 0 : null),
        is_active: formData.is_active ? 1 : 0
      };

      console.log('📤 Submitting data:', submitData);

      const res = await fetch(`/api/internal/scholarships?id=${id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(submitData),
      });

      const data = await res.json();

      if (!res.ok) {
        throw new Error(data.error || "Failed to update scholarship");
      }

      await Swal.fire({
        icon: 'success',
        title: 'Success!',
        text: 'Scholarship updated successfully!',
        confirmButtonColor: '#0B6D76',
      });
      
      router.push("/admin/scholarships");
    } catch (err) {
      console.error("Update Error:", err);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: err.message || "Something went wrong.",
        confirmButtonColor: '#0B6D76',
      });
    } finally {
      setLoading(false);
    }
  };

  const removeImage = () => {
    setFormData(prev => ({ ...prev, image: "" }));
    setImagePreview(null);
  };

  if (fetching) {
    return (
      <div className="p-6 bg-gradient-to-br from-purple-50 to-blue-100 min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#217484]"></div>
      </div>
    );
  }

  return (
    <div className="p-6 bg-gradient-to-br from-purple-50 to-blue-100 min-h-screen">
      {/* Header */}
      <div className="flex items-center gap-4 mb-6">
        <button
          onClick={() => router.push("/admin/scholarships")}
          className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
        >
          <ArrowLeft className="w-6 h-6 text-gray-600" />
        </button>
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold text-gray-900">Edit Scholarship</h1>
          <p className="text-gray-600 mt-1">Update scholarship details</p>
        </div>
      </div>

      {/* Form */}
      <form onSubmit={handleSubmit} className="bg-white rounded-2xl shadow-xl p-6 sm:p-8 max-w-4xl mx-auto">
        {/* Row 1: Title and Slug */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              Scholarship Title <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              name="title"
              value={formData.title}
              onChange={handleInputChange}
              required
              className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#217484] focus:border-transparent"
              placeholder="Enter scholarship title"
            />
          </div>

          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              Slug <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              name="slug"
              value={formData.slug}
              onChange={handleInputChange}
              required
              className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#217484] focus:border-transparent bg-gray-50"
              placeholder="Enter slug"
            />
            <p className="text-xs text-gray-500 mt-1">URL-friendly identifier</p>
          </div>
        </div>

        {/* Row 2: Country and Qualifications */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">Country</label>
            <select
              name="country_id"
              value={formData.country_id}
              onChange={handleSelectChange}
              className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#217484] focus:border-transparent"
            >
              <option value="">Select Country</option>
              {countries.map((country) => (
                <option key={country.id} value={country.id}>
                  {country.country} ({country.code})
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              Qualifications <span className="text-red-500">*</span>
            </label>
            <select
              name="qualification_ids"
              value={formData.qualification_ids}
              onChange={handleQualificationChange}
              multiple
              required
              className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#217484] focus:border-transparent min-h-32"
            >
              {qualifications.map((qualification) => (
                <option key={qualification.id} value={qualification.id}>
                  {qualification.title}
                </option>
              ))}
            </select>
            <p className="text-xs text-gray-500 mt-1">
              Hold Ctrl/Cmd to select multiple qualifications. {formData.qualification_ids.length} selected
            </p>
          </div>
        </div>

        {/* Row 3: Academic Requirements */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">Minimum CGPA</label>
            <input
              type="number"
              name="cgpa"
              value={formData.cgpa}
              onChange={handleInputChange}
              min="0"
              max="4"
              step="0.01"
              className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#217484] focus:border-transparent"
              placeholder="e.g., 3.0"
            />
            <p className="text-xs text-gray-500 mt-1">Scale: 0 - 4.0</p>
          </div>

          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">Percentage Cover (%)</label>
            <input
              type="number"
              name="percentage_cover"
              value={formData.percentage_cover}
              onChange={handleInputChange}
              min="0"
              max="100"
              step="1"
              className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#217484] focus:border-transparent"
              placeholder="e.g., 100"
            />
            <p className="text-xs text-gray-500 mt-1">0 - 100%</p>
          </div>

          {/* IELTS Field */}
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">IELTS Required</label>
            <select
              name="ielts"
              value={formData.ielts}
              onChange={handleSelectChange}
              className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#217484] focus:border-transparent"
            >
              <option value="">Select Option</option>
              <option value="1">Yes</option>
              <option value="0">No</option>
            </select>
            <p className="text-xs text-gray-500 mt-1">Is IELTS required?</p>
          </div>

          {/* Amount Range Field */}
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">Scholarship Amount Range</label>
            <div className="grid grid-cols-2 gap-2">
              <div>
                <input
                  type="number"
                  name="amount_min"
                  value={formData.amount_min}
                  onChange={handleInputChange}
                  min="0"
                  step="0.01"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent"
                  placeholder="Min"
                />
              </div>
              <div>
                <input
                  type="number"
                  name="amount_max"
                  value={formData.amount_max}
                  onChange={handleInputChange}
                  min="0"
                  step="0.01"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent"
                  placeholder="Max"
                />
              </div>
            </div>
            <p className="text-xs text-gray-500 mt-1">Amount range in currency</p>
          </div>
        </div>

        {/* Row 4: Deadline */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              Deadline <span className="text-red-500">*</span>
            </label>
            <div className="relative">
              <input
                type="date"
                name="deadline"
                value={formData.deadline}
                onChange={handleInputChange}
                required
                min={new Date().toISOString().split('T')[0]}
                className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#217484] focus:border-transparent"
              />
            </div>
          </div>
        </div>

        {/* Row 5: Image Upload */}
        <div className="mb-6">
          <label className="block text-sm font-semibold text-gray-700 mb-2">Scholarship Image</label>
          <div className="border-2 border-dashed border-gray-300 rounded-xl p-6 text-center hover:border-gray-400 transition-colors">
            {uploading ? (
              <div className="text-center">
                <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-[#217484] mx-auto mb-2"></div>
                <p className="text-sm text-gray-600">Uploading image...</p>
              </div>
            ) : imagePreview ? (
              <div>
                <Image
                  src={imagePreview}
                  alt="Preview"
                  width={120}
                  height={120}
                  className="w-24 h-24 object-cover rounded-lg mx-auto mb-2"
                />
                <p className="text-xs text-green-600 mb-2">✓ Image uploaded successfully</p>
                <button
                  type="button"
                  onClick={removeImage}
                  className="text-xs text-red-600 hover:text-red-800"
                >
                  Remove Image
                </button>
              </div>
            ) : (
              <>
                <Upload className="w-10 h-10 text-gray-400 mx-auto mb-2" />
                <p className="text-sm text-gray-600 mb-2">Click to upload an image</p>
              </>
            )}
            <input
              type="file"
              accept="image/*"
              onChange={handleImageChange}
              className="mt-2 text-sm mx-auto"
              disabled={uploading}
            />
            {!uploading && !imagePreview && (
              <p className="text-xs text-gray-500 mt-2">Supported formats: JPG, PNG, WebP (max 2MB)</p>
            )}
          </div>
        </div>

        {/* Row 6: Description with Summernote */}
        <div className="mb-6">
          <label className="block text-sm font-semibold text-gray-700 mb-2">Description</label>
          <SummernoteEditor
            value={formData.description}
            onChange={handleDescriptionChange}
            placeholder="Enter scholarship description..."
            height={300}
          />
        </div>

        {/* Row 7: FAQs Section */}
        <div className="mb-6">
          <div className="flex justify-between items-center mb-4">
            <label className="block text-sm font-semibold text-gray-700">
              Frequently Asked Questions <span className="text-red-500">*</span>
            </label>
            <button
              type="button"
              onClick={addFaq}
              className="flex items-center gap-2 px-3 py-2 text-sm bg-[#217484] text-white rounded-lg hover:bg-[#1a5d6b] transition-colors"
            >
              <Plus className="w-4 h-4" />
              Add FAQ
            </button>
          </div>
          
          <div className="space-y-4">
            {formData.faqs.map((faq, index) => (
              <div key={index} className="border border-gray-200 rounded-lg p-4 bg-gray-50">
                <div className="flex justify-between items-start mb-3">
                  <h4 className="text-sm font-medium text-gray-700">FAQ #{index + 1}</h4>
                  {formData.faqs.length > 1 && (
                    <button
                      type="button"
                      onClick={() => removeFaq(index)}
                      className="text-red-600 hover:text-red-800 p-1"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  )}
                </div>
                
                <div className="grid grid-cols-1 gap-3">
                  <div>
                    <label className="block text-xs font-medium text-gray-600 mb-1">Question</label>
                    <input
                      type="text"
                      value={faq.question}
                      onChange={(e) => handleFaqChange(index, 'question', e.target.value)}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent"
                      placeholder="Enter question..."
                      required
                    />
                  </div>
                  
                  <div>
                    <label className="block text-xs font-medium text-gray-600 mb-1">Answer</label>
                    <textarea
                      value={faq.answer}
                      onChange={(e) => handleFaqChange(index, 'answer', e.target.value)}
                      rows={3}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent"
                      placeholder="Enter answer..."
                      required
                    />
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Row 8: Active Checkbox */}
        <div className="flex items-center gap-3 mb-6">
          <input
            type="checkbox"
            name="is_active"
            id="is_active"
            checked={formData.is_active}
            onChange={handleCheckboxChange}
            className="w-4 h-4 text-[#217484] rounded focus:ring-[#217484]"
          />
          <label htmlFor="is_active" className="text-sm font-medium text-gray-700">
            Active Scholarship
          </label>
        </div>

        {/* Submit Button */}
        <div className="flex justify-end mt-8 pt-6 border-t">
          <button
            type="submit"
            disabled={loading || uploading}
            className={`px-8 py-3 rounded-xl flex items-center gap-2 transition-all ${
              loading || uploading
                ? 'bg-gray-400 cursor-not-allowed'
                : 'bg-[#217484] text-white hover:bg-[#1a5d6b] hover:shadow-xl'
            }`}
          >
            {loading ? (
              <>
                <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                <span>Updating Scholarship...</span>
              </>
            ) : (
              <>
                <Save className="w-5 h-5" />
                <span>Update Scholarship</span>
              </>
            )}
          </button>
        </div>
      </form>
    </div>
  );
};

export default EditScholarship;