"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import dynamic from 'next/dynamic';
import Swal from 'sweetalert2';
import { ArrowLeft, Save, FileText, List, Type } from "lucide-react";

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

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

const AddSiloRouteDetail = () => {
  const router = useRouter();
  const [activeTab, setActiveTab] = useState('GENERAL');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  
  // Silo routes state
  const [siloRoutes, setSiloRoutes] = useState([]);
  const [loadingSiloRoutes, setLoadingSiloRoutes] = useState(true);

  // FAQs state
  const [faqs, setFaqs] = useState([
    {
      question: '',
      answer: '',
    }
  ]);

  // Form data
  const [formData, setFormData] = useState({
    silo_route_id: '',
    simple_title: '',
    color_title: '',
    slug: '',
    short_description: '',
    top_content: '',
    middle_content: '',
    bottom_content: '',
    meta_title: '',
    meta_description: '',
    faqs: JSON.stringify([]),
  });

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

  // Fetch silo routes on component mount
  useEffect(() => {
    fetchSiloRoutes();
  }, []);

  const fetchSiloRoutes = async () => {
    try {
      setLoadingSiloRoutes(true);
      const res = await fetch('/api/internal/silo-routes/list');
      if (!res.ok) throw new Error('Failed to fetch silo routes');
      
      const data = await res.json();
      
      if (data.success) {
        setSiloRoutes(data.data || []);
      } else {
        throw new Error(data.error || 'Failed to load silo routes');
      }
    } catch (error) {
      console.error('Error fetching silo routes:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to load silo routes. Please refresh the page.',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setLoadingSiloRoutes(false);
    }
  };

  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
      }));
    }
  };

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

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

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

  const handleBottomContentChange = (content) => {
    setFormData(prev => ({
      ...prev,
      bottom_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.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();
    
    // 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;
    }
    
    setIsSubmitting(true);

    try {
      const response = await fetch('/api/internal/silo-route-details', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || 'Failed to create silo route detail');
      }

      await Swal.fire({
        icon: 'success',
        title: 'Success!',
        text: 'Silo route detail created successfully!',
        confirmButtonColor: '#0B6D76'
      });

      router.push('/admin/silo-route-details');
    } catch (error) {
      console.error('Submit error:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: error.message || 'Something went wrong',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const renderGeneral = () => (
    <div className="space-y-6">
      {/* Silo Route Selection */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          <div className="flex items-center gap-2">
            <List className="w-4 h-4" />
            Select Silo Route
          </div>
        </label>
        <select
          name="silo_route_id"
          value={formData.silo_route_id}
          onChange={handleChange}
          className="w-full border px-4 py-2 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
          disabled={loadingSiloRoutes}
        >
          <option value="">
            {loadingSiloRoutes ? 'Loading silo routes...' : '-- Select a Silo Route --'}
          </option>
          {siloRoutes.map((route) => (
            <option key={route.id} value={route.id}>
              {route.name} ({route.slug})
            </option>
          ))}
        </select>
        {loadingSiloRoutes && (
          <p className="text-xs text-gray-500 mt-1">Loading silo routes...</p>
        )}
        {!loadingSiloRoutes && siloRoutes.length === 0 && (
          <p className="text-xs text-amber-600 mt-1">
            No silo routes found. Please create a silo route first.
          </p>
        )}
      </div>

      {/* 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-[#0B6D76] 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-[#0B6D76] 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>

      {/* 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-[#0B6D76] 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>

      {/* Middle Content */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Middle Content
        </label>
        <SummernoteEditor
          value={formData.middle_content}
          onChange={handleMiddleContentChange}
        />
      </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 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-[#0B6D76] 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-[#0B6D76] 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-[#0B6D76] 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-[#0B6D76] 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 '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 Detail</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={isSubmitting}
                >
                  {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 Detail</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={isSubmitting}
              >
                {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-route-details')}
              className="bg-gray-300 text-gray-800 px-6 py-2 rounded-lg hover:bg-gray-400 transition-colors"
              disabled={isSubmitting}
            >
              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={isSubmitting}
            >
              {isSubmitting ? (
                <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 AddSiloRouteDetail;