"use client";

import { useState } from "react";
import { ArrowLeft, Save, FileText, Type, Image, AlignLeft, Upload, X } from "lucide-react";
import { useRouter } from "next/navigation";
import dynamic from 'next/dynamic';
import Swal from 'sweetalert2';

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

const tabs = [
  'GENERAL',
  'CONTENT',
  'ABOUT SECTION',
  'META & FAQ',
];

const AddSiloRoute = () => {
  const router = useRouter();
  const [activeTab, setActiveTab] = useState('GENERAL');
  const [loading, setLoading] = useState(false);
  const [imageUploading, setImageUploading] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  
  // FAQs state
  const [faqs, setFaqs] = useState([
    {
      question: '',
      answer: '',
    }
  ]);

  // Form data
  const [formData, setFormData] = useState({
    simple_title: '',
    color_title: '',
    name: '',
    slug: '',
    short_description: '',
    top_content: '',
    bottom_content: '',
    about_title: '',
    about_content: '',
    about_image: '',
    about_image_alt_text: '',
    about_image_direction: 'left',
    meta_title: '',
    meta_description: '',
    faqs: JSON.stringify([]),
  });

  const [validationErrors, setValidationErrors] = useState({});

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
    
    // Clear validation error for this field
    if (validationErrors[name]) {
      setValidationErrors(prev => ({
        ...prev,
        [name]: undefined
      }));
    }
  };

  // Image upload handler
  const handleImageUpload = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    // Validate file type
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
    if (!allowedTypes.includes(file.type)) {
      Swal.fire({
        icon: 'error',
        title: 'Invalid File Type',
        text: 'Please upload only JPG, PNG, GIF, or WebP images.',
        confirmButtonColor: '#0B6D76',
      });
      return;
    }

    // Validate file size (max 2MB)
    if (file.size > 2 * 1024 * 1024) {
      Swal.fire({
        icon: 'error',
        title: 'File Too Large',
        text: 'Image size should be less than 2MB.',
        confirmButtonColor: '#0B6D76',
      });
      return;
    }

    try {
      setImageUploading(true);
      const uploadFormData = new FormData();
      uploadFormData.append('image', file);
      uploadFormData.append('uploadType', 'silo-routes'); // Custom folder for silo routes

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

      const data = await res.json();
      
      if (data.success && data.url) {
        setFormData(prev => ({ 
          ...prev, 
          about_image: data.url
        }));
        Swal.fire({
          icon: 'success',
          title: 'Success!',
          text: 'Image uploaded successfully!',
          confirmButtonColor: '#0B6D76',
          timer: 1500,
          showConfirmButton: false
        });
      } else {
        Swal.fire({
          icon: 'error',
          title: 'Upload Failed',
          text: data.message || 'Image upload failed. Please try again.',
          confirmButtonColor: '#0B6D76',
        });
      }
    } catch (error) {
      console.error('Upload error:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: 'Image upload failed. Please check your connection and try again.',
        confirmButtonColor: '#0B6D76',
      });
    } finally {
      setImageUploading(false);
      // Clear the file input
      e.target.value = '';
    }
  };

  const removeImage = () => {
    setFormData(prev => ({
      ...prev,
      about_image: '',
      about_image_alt_text: '' // Optional: clear alt text as well
    }));
  };

  // Separate handlers for each editor
  const handleShortDescriptionChange = (content) => {
    setFormData(prev => ({
      ...prev,
      short_description: content || ''
    }));
  };

  const handleTopContentChange = (content) => {
    setFormData(prev => ({
      ...prev,
      top_content: content || ''
    }));
  };

  const handleBottomContentChange = (content) => {
    setFormData(prev => ({
      ...prev,
      bottom_content: content || ''
    }));
  };

  const handleAboutContentChange = (content) => {
    setFormData(prev => ({
      ...prev,
      about_content: content || ''
    }));
  };

  // FAQs handlers
  const handleFaqChange = (index, field, value) => {
    const updatedFaqs = [...faqs];
    updatedFaqs[index][field] = value;
    setFaqs(updatedFaqs);
    setFormData(prev => ({
      ...prev,
      faqs: JSON.stringify(updatedFaqs),
    }));
  };

  const addFaq = () => {
    setFaqs([
      ...faqs,
      {
        question: '',
        answer: '',
      }
    ]);
  };

  const removeFaq = (index) => {
    if (faqs.length > 1) {
      const updatedFaqs = [...faqs];
      updatedFaqs.splice(index, 1);
      setFaqs(updatedFaqs);
      setFormData(prev => ({
        ...prev,
        faqs: JSON.stringify(updatedFaqs),
      }));
    }
  };

  const validateForm = () => {
    const errors = {};
    
    if (!formData.simple_title.trim()) {
      errors.simple_title = "Simple title is required";
    }
    
    if (!formData.name.trim()) {
      errors.name = "Name is required";
    }
    
    if (formData.slug && formData.slug.includes(' ')) {
      errors.slug = "Slug cannot contain spaces";
    }
    
    if (formData.slug && !/^[a-z0-9-]+$/.test(formData.slug)) {
      errors.slug = "Slug can only contain lowercase letters, numbers, and hyphens";
    }
    
    return errors;
  };

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

    // Validate form
    const errors = validateForm();
    if (Object.keys(errors).length > 0) {
      setValidationErrors(errors);
      Swal.fire({
        icon: 'error',
        title: 'Validation Error',
        html: Object.values(errors).map(error => `<p>• ${error}</p>`).join(''),
        confirmButtonColor: '#0B6D76',
      });
      return;
    }

    try {
      setLoading(true);
      
      const res = await fetch("/api/internal/silo-routes", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      });

      const data = await res.json();

      if (!res.ok) {
        throw new Error(data.error || "Failed to add silo route");
      }

      await Swal.fire({
        icon: 'success',
        title: 'Success!',
        text: 'Silo route added successfully!',
        confirmButtonColor: '#0B6D76',
      });
      
      router.push("/admin/silo-routes");
    } catch (err) {
      console.error("Submit Error:", err);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: err.message || "Something went wrong.",
        confirmButtonColor: '#0B6D76',
      });
    } finally {
      setLoading(false);
    }
  };

  const renderGeneral = () => (
    <div className="space-y-6">
      {/* Title Section - Split into two */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Simple Title */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            <div className="flex items-center gap-2">
              <Type className="w-4 h-4" />
              Simple Title <span className="text-red-500">*</span>
            </div>
          </label>
          <input
            type="text"
            name="simple_title"
            value={formData.simple_title}
            onChange={handleChange}
            className={`w-full border px-4 py-2 rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent ${
              validationErrors.simple_title ? 'border-red-300' : 'border-gray-300'
            }`}
            placeholder="Enter main title"
            required
          />
          {validationErrors.simple_title && (
            <p className="text-red-500 text-xs mt-1">{validationErrors.simple_title}</p>
          )}
        </div>

        {/* Color Title */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            <div className="flex items-center gap-2">
              <span className="w-4 h-4 rounded-full bg-gradient-to-r from-purple-500 to-pink-500"></span>
              Color Title
            </div>
          </label>
          <input
            type="text"
            name="color_title"
            value={formData.color_title}
            onChange={handleChange}
            className="w-full border border-gray-300 px-4 py-2 rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent"
            placeholder="Enter colored/highlighted title (optional)"
          />
          <p className="text-xs text-gray-500 mt-1">
            This part can be styled with different colors in the frontend
          </p>
        </div>
      </div>

      {/* Name */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          Name <span className="text-red-500">*</span>
        </label>
        <input
          type="text"
          name="name"
          value={formData.name}
          onChange={handleChange}
          className={`w-full border px-4 py-2 rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent ${
            validationErrors.name ? 'border-red-300' : 'border-gray-300'
          }`}
          placeholder="Enter display name"
          required
        />
        {validationErrors.name && (
          <p className="text-red-500 text-xs mt-1">{validationErrors.name}</p>
        )}
      </div>

      {/* Slug */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          Slug
        </label>
        <input
          type="text"
          name="slug"
          value={formData.slug}
          onChange={handleChange}
          className={`w-full border px-4 py-2 rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent ${
            validationErrors.slug ? 'border-red-300' : 'border-gray-300'
          }`}
          placeholder="page-url-slug (auto-generated if empty)"
        />
        {validationErrors.slug && (
          <p className="text-red-500 text-xs mt-1">{validationErrors.slug}</p>
        )}
        <p className="text-xs text-gray-500 mt-1">
          URL-friendly identifier. Leave empty to auto-generate from simple title.
        </p>
      </div>

      {/* Short Description - Summernote */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Short Description
        </label>
        <SummernoteEditor
          value={formData.short_description}
          onChange={handleShortDescriptionChange}
        />
      </div>
    </div>
  );

  const renderContent = () => (
    <div className="space-y-8">
      {/* Top Content */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Top Content
        </label>
        <SummernoteEditor
          value={formData.top_content}
          onChange={handleTopContentChange}
        />
      </div>

      {/* Bottom Content */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Bottom Content
        </label>
        <SummernoteEditor
          value={formData.bottom_content}
          onChange={handleBottomContentChange}
        />
      </div>
    </div>
  );

  const renderAboutSection = () => (
    <div className="space-y-6">
      <div className="flex items-center gap-2 mb-4">
        <Image className="w-5 h-5 text-[#0B6D76]" />
        <h3 className="text-lg font-medium text-gray-800">About Section</h3>
      </div>
      
      {/* About Title */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          About Title
        </label>
        <input
          type="text"
          name="about_title"
          value={formData.about_title}
          onChange={handleChange}
          className="w-full border px-4 py-2 rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent"
          placeholder="Enter about section title (optional)"
        />
        <p className="text-xs text-gray-500 mt-1">
          Leave empty to hide the about section
        </p>
      </div>

      {/* About Content */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          About Content
        </label>
        <SummernoteEditor
          value={formData.about_content}
          onChange={handleAboutContentChange}
        />
      </div>

      {/* About Image Upload */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          About Image
        </label>
        
        {formData.about_image ? (
          <div className="border rounded-lg p-4 bg-gray-50">
            <div className="flex items-start gap-4">
              <div className="relative w-32 h-32 rounded-lg overflow-hidden bg-gray-200">
                <img 
                  src={formData.about_image} 
                  alt={formData.about_image_alt_text || 'About preview'}
                  className="w-full h-full object-cover"
                />
              </div>
              <div className="flex-1">
                <p className="text-sm text-gray-600 mb-2">
                  Image uploaded successfully
                </p>
                <button
                  type="button"
                  onClick={removeImage}
                  className="text-sm text-red-600 hover:text-red-800 flex items-center gap-1"
                >
                  <X className="w-4 h-4" />
                  Remove Image
                </button>
              </div>
            </div>
          </div>
        ) : (
          <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-gray-400 transition-colors">
            <Upload className="w-8 h-8 text-gray-400 mx-auto mb-2" />
            <p className="text-sm text-gray-500 mb-2">
              Click to upload or drag and drop
            </p>
            <p className="text-xs text-gray-400 mb-3">
              JPG, PNG, GIF, WebP up to 2MB
            </p>
            <label className="cursor-pointer">
              <span className="px-4 py-2 bg-[#217484] text-white rounded-lg hover:bg-[#1a5d6b] transition-colors inline-flex items-center gap-2">
                <Upload className="w-4 h-4" />
                {imageUploading ? 'Uploading...' : 'Choose Image'}
              </span>
              <input
                type="file"
                accept="image/jpeg,image/jpg,image/png,image/gif,image/webp"
                onChange={handleImageUpload}
                className="hidden"
                disabled={imageUploading}
              />
            </label>
            {imageUploading && (
              <div className="mt-3">
                <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-[#217484] mx-auto"></div>
                <p className="text-xs text-gray-500 mt-1">Uploading image...</p>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Image Alt Text */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Image Alt Text
        </label>
        <input
          type="text"
          name="about_image_alt_text"
          value={formData.about_image_alt_text}
          onChange={handleChange}
          className="w-full border px-4 py-2 rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent"
          placeholder="Descriptive alt text for image (important for SEO)"
          disabled={!formData.about_image}
        />
        <p className="text-xs text-gray-500 mt-1">
          Describe what the image shows (required for accessibility and SEO)
        </p>
      </div>

      {/* Image Direction */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          <div className="flex items-center gap-2">
            <AlignLeft className="w-4 h-4" />
            Image Position
          </div>
        </label>
        <div className="flex gap-6">
          <label className="flex items-center">
            <input
              type="radio"
              name="about_image_direction"
              value="left"
              checked={formData.about_image_direction === 'left'}
              onChange={handleChange}
              className="mr-2"
              disabled={!formData.about_image}
            />
            Left (Image on left, text on right)
          </label>
          <label className="flex items-center">
            <input
              type="radio"
              name="about_image_direction"
              value="right"
              checked={formData.about_image_direction === 'right'}
              onChange={handleChange}
              className="mr-2"
              disabled={!formData.about_image}
            />
            Right (Image on right, text on left)
          </label>
        </div>
        <p className="text-xs text-gray-500 mt-1">
          Choose which side the image appears on (only applies when image is uploaded)
        </p>
      </div>
    </div>
  );

  const renderMetaFaq = () => (
    <div className="space-y-8">
      {/* Meta Information */}
      <div className="space-y-6">
        <h3 className="text-lg font-medium text-gray-800">SEO Meta Information</h3>
        
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Meta Title
          </label>
          <input
            type="text"
            name="meta_title"
            value={formData.meta_title}
            onChange={handleChange}
            className="w-full border px-4 py-2 rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent"
            placeholder="SEO title (max 60 characters)"
            maxLength={60}
          />
          <p className="text-xs text-gray-500 mt-1">
            {formData.meta_title.length}/60 characters
          </p>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Meta Description
          </label>
          <textarea
            name="meta_description"
            value={formData.meta_description}
            onChange={handleChange}
            className="w-full border px-4 py-2 rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent"
            rows={4}
            placeholder="SEO description (max 160 characters)"
            maxLength={160}
          />
          <p className="text-xs text-gray-500 mt-1">
            {formData.meta_description.length}/160 characters
          </p>
        </div>
      </div>

      {/* FAQs Section */}
      <div className="space-y-6">
        <div className="flex justify-between items-center">
          <h3 className="text-lg font-medium text-gray-800">Frequently Asked Questions (FAQs)</h3>
          <button
            type="button"
            onClick={addFaq}
            className="bg-green-500 text-white px-4 py-2 rounded-lg text-sm hover:bg-green-600"
          >
            Add FAQ
          </button>
        </div>

        <p className="text-sm text-gray-600">
          Add common questions and answers for this page.
        </p>

        {faqs.map((faq, index) => (
          <div key={index} className="p-6 border border-gray-300 rounded-lg space-y-4 bg-gray-50">
            <div className="flex justify-between items-center">
              <h4 className="text-md font-medium text-gray-700">FAQ #{index + 1}</h4>
              {faqs.length > 1 && (
                <button
                  type="button"
                  onClick={() => removeFaq(index)}
                  className="text-red-600 text-sm hover:text-red-800"
                >
                  Remove
                </button>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Question*
              </label>
              <input
                type="text"
                value={faq.question}
                onChange={(e) => handleFaqChange(index, 'question', e.target.value)}
                className="w-full border px-4 py-2 rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent"
                placeholder="e.g., What is this page about?"
                required
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Answer*
              </label>
              <textarea
                value={faq.answer}
                onChange={(e) => handleFaqChange(index, 'answer', e.target.value)}
                className="w-full border px-4 py-2 rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent"
                rows={4}
                placeholder="Provide a detailed answer..."
                required
              />
            </div>
          </div>
        ))}

        {faqs.length === 0 && (
          <div className="text-center py-12 border-2 border-dashed border-gray-300 rounded-lg">
            <FileText className="w-12 h-12 text-gray-400 mx-auto mb-4" />
            <p className="text-gray-500">No FAQs added yet.</p>
            <button
              type="button"
              onClick={addFaq}
              className="mt-4 bg-green-500 text-white px-6 py-2 rounded-lg text-sm hover:bg-green-600"
            >
              Add First FAQ
            </button>
          </div>
        )}
      </div>
    </div>
  );

  const renderContentByTab = () => {
    switch (activeTab) {
      case 'GENERAL':
        return renderGeneral();
      case 'CONTENT':
        return renderContent();
      case 'ABOUT SECTION':
        return renderAboutSection();
      case 'META & FAQ':
        return renderMetaFaq();
      default:
        return null;
    }
  };

  return (
    <form onSubmit={handleSubmit} className="min-h-screen flex flex-col md:flex-row bg-gray-100">
      {/* Mobile Menu Button */}
      <div className="md:hidden bg-white p-4 flex justify-between items-center border-b">
        <h2 className="text-xl font-bold text-gray-800">Add Silo Route</h2>
        <button
          type="button"
          onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
          className="text-gray-500 hover:text-gray-600"
        >
          <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            {mobileMenuOpen ? (
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            ) : (
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
            )}
          </svg>
        </button>
      </div>

      {/* Sidebar - Mobile */}
      {mobileMenuOpen && (
        <div className="md:hidden bg-white border-b shadow-lg p-4">
          <ul className="space-y-2">
            {tabs.map((tab) => (
              <li key={tab}>
                <button
                  type="button"
                  onClick={() => {
                    setActiveTab(tab);
                    setMobileMenuOpen(false);
                  }}
                  className={`w-full text-left px-4 py-2 rounded-lg transition-colors ${
                    activeTab === tab ? 'bg-[#0B6D76] text-white' : 'hover:bg-gray-200'
                  }`}
                  disabled={loading}
                >
                  {tab}
                </button>
              </li>
            ))}
          </ul>
        </div>
      )}

      {/* Sidebar - Desktop */}
      <div className="hidden md:block w-64 bg-white border-r shadow-lg p-6">
        <h2 className="text-xl font-bold mb-6 text-gray-800">Add Silo Route</h2>
        <ul className="space-y-2">
          {tabs.map((tab) => (
            <li key={tab}>
              <button
                type="button"
                onClick={() => setActiveTab(tab)}
                className={`w-full text-left px-4 py-2 rounded-lg transition-colors ${
                  activeTab === tab ? 'bg-[#0B6D76] text-white' : 'hover:bg-gray-200'
                }`}
                disabled={loading}
              >
                {tab}
              </button>
            </li>
          ))}
        </ul>
      </div>

      {/* Content Area */}
      <div className="flex-1 p-4 md:p-10 bg-white">
        <div className="max-w-4xl mx-auto">
          {/* Mobile Tab Indicator */}
          <div className="md:hidden mb-6">
            <div className="bg-[#0B6D76] text-white px-4 py-2 rounded-lg">
              {activeTab}
            </div>
          </div>

          {renderContentByTab()}

          {/* Submit Buttons */}
          <div className="flex flex-col-reverse md:flex-row justify-end mt-8 space-y-4 md:space-y-0 space-x-0 md:space-x-4">
            <button
              type="button"
              onClick={() => router.push('/admin/silo-routes')}
              className="bg-gray-300 text-gray-800 px-6 py-2 rounded-lg hover:bg-gray-400 transition-colors"
              disabled={loading || imageUploading}
            >
              Cancel
            </button>
            <button
              type="submit"
              className="bg-[#0B6D76] text-white px-6 py-2 rounded-lg hover:bg-[#09545c] transition-colors disabled:opacity-50 disabled:cursor-not-allowed mb-4 md:mb-0"
              disabled={loading || imageUploading}
            >
              {loading ? (
                <span className="flex items-center justify-center">
                  <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  Saving...
                </span>
              ) : (
                <>
                  <Save className="w-4 h-4 inline mr-2" />
                  Save
                </>
              )}
            </button>
          </div>
        </div>
      </div>
    </form>
  );
};

export default AddSiloRoute;