
import React, { useState, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { useData } from '../../context/DataContext';
import { useToast } from '../../context/ToastContext';
import { FormField } from '../../types';

export const DynamicPage: React.FC = () => {
  const location = useLocation();
  const { dynamicPages, customForms } = useData();
  const { addToast } = useToast();
  
  const pageId = location.pathname.split('/doctor/page-')[1];
  const page = dynamicPages.find(p => p.id === pageId);
  const form = customForms.find(f => f.id === page?.connectedFormId);

  const [formData, setFormData] = useState<Record<string, any>>({});
  const [currentStep, setCurrentStep] = useState(0);
  
  // Accordion State
  const [openAccordions, setOpenAccordions] = useState<Record<string, number | null>>({});

  useEffect(() => {
      setFormData({});
      setCurrentStep(0);
  }, [pageId]);

  if (!page || !form) return (
      <div className="h-full flex flex-col items-center justify-center text-gray-400">
          <i className="fas fa-unlink text-4xl mb-4"></i>
          <p className="text-lg">الصفحة غير متوفرة</p>
      </div>
  );

  // Split fields into pages based on 'page_break'
  const steps = form.fields.reduce((acc, field) => {
      if (field.type === 'page_break') {
          acc.push([]);
      } else {
          acc[acc.length - 1].push(field);
      }
      return acc;
  }, [[]] as FormField[][]);

  const isLastStep = currentStep === steps.length - 1;

  const handleNext = () => {
      if (currentStep < steps.length - 1) setCurrentStep(prev => prev + 1);
  };

  const handlePrev = () => {
      if (currentStep > 0) setCurrentStep(prev => prev - 1);
  };

  const handleSubmit = (e: React.FormEvent) => {
      e.preventDefault();
      console.log('Submitted:', formData);
      addToast('تم إرسال البيانات بنجاح', 'success');
      setFormData({});
      setCurrentStep(0);
  };

  const handleInputChange = (id: string, value: any) => {
      setFormData(prev => ({ ...prev, [id]: value }));
  };

  const toggleAccordion = (fieldId: string, index: number) => {
      setOpenAccordions(prev => ({
          ...prev,
          [fieldId]: prev[fieldId] === index ? null : index
      }));
  };

  // Animation Classes Helper
  const getAnimClass = (anim?: string) => {
      if (anim === 'fade-in') return 'animate-fade-in';
      if (anim === 'slide-up') return 'animate-slide-up';
      if (anim === 'zoom-in') return 'animate-[zoomIn_0.5s_ease-out]';
      if (anim === 'bounce') return 'animate-bounce';
      return '';
  };

  const renderField = (field: FormField) => {
      const colSpan = field.width === 'full' ? 'md:col-span-12' : field.width === 'half' ? 'md:col-span-6' : 'md:col-span-4';
      const anim = getAnimClass(field.animation);

      switch (field.type) {
          case 'header':
              return <h3 className={`text-2xl font-bold text-gray-800 border-b pb-2 mb-4 ${colSpan} ${anim}`}>{field.label}</h3>;
          case 'paragraph':
              return <p className={`text-gray-600 leading-relaxed mb-4 ${colSpan} ${anim}`}>{field.label}</p>;
          case 'divider':
              return <hr className={`border-gray-200 my-4 ${colSpan}`} />;
          
          case 'html_block':
              return <div className={`${colSpan} ${anim}`} dangerouslySetInnerHTML={{__html: field.defaultValue || ''}} />;

          case 'video':
              return (
                  <div className={`${colSpan} aspect-video rounded-2xl overflow-hidden shadow-lg border border-gray-200 bg-black ${anim}`}>
                      <iframe 
                        width="100%" 
                        height="100%" 
                        src={field.defaultValue} 
                        title={field.label} 
                        frameBorder="0" 
                        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
                        allowFullScreen
                      ></iframe>
                  </div>
              );

          case 'map':
              return (
                  <div className={`${colSpan} h-72 rounded-2xl overflow-hidden shadow-md border border-gray-200 bg-gray-100 ${anim}`}>
                      <iframe 
                        width="100%" 
                        height="100%" 
                        src={field.defaultValue} 
                        frameBorder="0" 
                        style={{border:0}} 
                        aria-hidden="false" 
                        title={field.label}
                      ></iframe>
                  </div>
              );

          case 'navigation':
              return (
                  <nav className={`flex gap-4 p-4 bg-white shadow-sm rounded-xl mb-6 items-center justify-center ${colSpan} ${anim}`}>
                      {field.options?.map((opt, i) => (
                          <button key={i} type="button" className="text-gray-600 hover:text-primary font-medium transition-colors">{opt}</button>
                      ))}
                  </nav>
              );

          case 'cta_button':
              return (
                  <div className={`${colSpan} flex justify-center my-4 ${anim}`}>
                      <a 
                        href={field.defaultValue || '#'} 
                        className="bg-primary hover:bg-primary-dark text-white px-8 py-3 rounded-full font-bold shadow-lg hover:shadow-xl transform hover:-translate-y-1 transition-all flex items-center gap-2"
                      >
                          {field.label} <i className="fas fa-arrow-right"></i>
                      </a>
                  </div>
              );

          case 'social_share':
              return (
                  <div className={`${colSpan} flex gap-3 my-2 ${anim}`}>
                      <button type="button" className="w-10 h-10 bg-[#1877F2] text-white rounded-full shadow hover:opacity-90 flex items-center justify-center"><i className="fab fa-facebook-f"></i></button>
                      <button type="button" className="w-10 h-10 bg-[#1DA1F2] text-white rounded-full shadow hover:opacity-90 flex items-center justify-center"><i className="fab fa-twitter"></i></button>
                      <button type="button" className="w-10 h-10 bg-[#25D366] text-white rounded-full shadow hover:opacity-90 flex items-center justify-center"><i className="fab fa-whatsapp"></i></button>
                      <button type="button" className="w-10 h-10 bg-gray-800 text-white rounded-full shadow hover:opacity-90 flex items-center justify-center"><i className="fas fa-envelope"></i></button>
                  </div>
              );

          case 'progress_bar':
              const pct = Math.min(Math.max(Number(field.defaultValue) || 0, 0), 100);
              return (
                  <div className={`${colSpan} my-2 ${anim}`}>
                      <div className="flex justify-between mb-1">
                          <span className="text-sm font-bold text-gray-700">{field.label}</span>
                          <span className="text-sm font-bold text-primary">{pct}%</span>
                      </div>
                      <div className="w-full bg-gray-200 rounded-full h-3">
                          <div className="bg-primary h-3 rounded-full transition-all duration-1000" style={{ width: `${pct}%` }}></div>
                      </div>
                  </div>
              );

          case 'countdown':
              return (
                  <div className={`${colSpan} my-4 ${anim}`}>
                      <div className="bg-gradient-to-r from-red-500 to-red-600 text-white p-6 rounded-2xl text-center shadow-lg">
                          <h4 className="text-xl font-bold mb-4">{field.label}</h4>
                          <div className="flex justify-center gap-4 text-center" dir="ltr">
                              <div className="bg-black/20 rounded-lg p-2 min-w-[60px]"><div className="text-3xl font-mono font-bold">02</div><div className="text-[10px] uppercase opacity-75">Days</div></div>
                              <div className="bg-black/20 rounded-lg p-2 min-w-[60px]"><div className="text-3xl font-mono font-bold">14</div><div className="text-[10px] uppercase opacity-75">Hours</div></div>
                              <div className="bg-black/20 rounded-lg p-2 min-w-[60px]"><div className="text-3xl font-mono font-bold">35</div><div className="text-[10px] uppercase opacity-75">Mins</div></div>
                          </div>
                      </div>
                  </div>
              );

          case 'accordion':
              return (
                  <div className={`${colSpan} space-y-2 ${anim}`}>
                      {field.label && <h4 className="font-bold text-gray-800 mb-2">{field.label}</h4>}
                      {field.options?.map((opt, i) => {
                          const [q, a] = opt.split('|');
                          const isOpen = openAccordions[field.id] === i;
                          return (
                              <div key={i} className="border border-gray-200 rounded-lg overflow-hidden transition-all bg-white">
                                  <button 
                                    type="button"
                                    onClick={() => toggleAccordion(field.id, i)}
                                    className={`w-full px-4 py-3 text-right font-bold flex justify-between items-center ${isOpen ? 'bg-blue-50 text-primary' : 'bg-white text-gray-800 hover:bg-gray-50'}`}
                                  >
                                      {q}
                                      <i className={`fas fa-chevron-down transition-transform ${isOpen ? 'rotate-180' : ''}`}></i>
                                  </button>
                                  {isOpen && (
                                      <div className="p-4 bg-white text-gray-600 text-sm leading-relaxed border-t border-gray-100 animate-slide-up">
                                          {a || 'No content provided'}
                                      </div>
                                  )}
                              </div>
                          );
                      })}
                  </div>
              );

          case 'chart':
              return (
                  <div className={`${colSpan} bg-white p-4 rounded-xl border border-gray-100 shadow-sm ${anim}`}>
                      <h4 className="font-bold text-gray-700 mb-4">{field.label}</h4>
                      <div className="flex items-end gap-2 h-40">
                          {field.options?.map((opt, i) => {
                              const [label, val] = opt.split(',');
                              const height = Math.min(Number(val) || 0, 100);
                              return (
                                  <div key={i} className="flex-1 flex flex-col items-center group">
                                      <div className="w-full bg-blue-100 rounded-t-lg relative group-hover:bg-blue-200 transition-colors" style={{ height: `${height}%` }}>
                                          <span className="absolute -top-6 left-1/2 -translate-x-1/2 text-xs font-bold opacity-0 group-hover:opacity-100 transition-opacity">{val}</span>
                                      </div>
                                      <span className="text-[10px] text-gray-500 mt-1">{label}</span>
                                  </div>
                              );
                          })}
                      </div>
                  </div>
              );

          case 'alert_box':
              return (
                  <div className={`${colSpan} p-4 rounded-xl mb-4 flex items-start gap-3 ${field.defaultValue === 'warning' ? 'bg-yellow-50 text-yellow-800 border border-yellow-200' : 'bg-blue-50 text-blue-800 border border-blue-200'} ${anim}`}>
                      <i className={`fas ${field.defaultValue === 'warning' ? 'fa-exclamation-triangle' : 'fa-info-circle'} mt-1`}></i>
                      <div>
                          <h5 className="font-bold">{field.label}</h5>
                          <p className="text-sm opacity-90">{field.placeholder}</p>
                      </div>
                  </div>
              );

          case 'interactive_image':
              return (
                  <div className={`${colSpan} group overflow-hidden rounded-xl relative shadow-lg ${anim}`}>
                      <img 
                        src={field.placeholder || 'https://placehold.co/600x300'} 
                        alt={field.label} 
                        className="w-full h-auto transition-transform duration-700 group-hover:scale-110" 
                      />
                      <div className="absolute inset-0 bg-gradient-to-t from-black/70 to-transparent flex items-end p-6 opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                          <p className="text-white font-bold text-lg">{field.label}</p>
                      </div>
                  </div>
              );

          // Standard Inputs
          case 'address':
              return (
                  <div className={`${colSpan} space-y-2 ${anim}`}>
                      <label className="font-bold text-gray-700">{field.label}</label>
                      <div className="grid grid-cols-2 gap-2">
                          <input type="text" placeholder="المدينة" className="p-3 border rounded-lg focus:ring-primary focus:border-primary bg-white text-gray-900" onChange={e => handleInputChange(`${field.id}_city`, e.target.value)} />
                          <input type="text" placeholder="الشارع" className="p-3 border rounded-lg focus:ring-primary focus:border-primary bg-white text-gray-900" onChange={e => handleInputChange(`${field.id}_street`, e.target.value)} />
                      </div>
                  </div>
              );
          
          case 'phone_input':
              return (
                  <div className={`${colSpan} ${anim}`}>
                      <label className="font-bold text-gray-700 mb-1 block">{field.label}</label>
                      <div className="relative">
                          <input 
                            type="tel" 
                            className="w-full pl-4 pr-10 py-3 border rounded-xl focus:ring-primary focus:border-primary bg-white text-gray-900 ltr" 
                            placeholder="+966..."
                            onChange={e => handleInputChange(field.id, e.target.value)}
                          />
                          <i className="fas fa-phone absolute right-3 top-3.5 text-gray-400"></i>
                      </div>
                  </div>
              );

          case 'rating':
              return (
                  <div className={`${colSpan} ${anim}`}>
                      <label className="font-bold text-gray-700 mb-1 block">{field.label}</label>
                      <div className="flex gap-2">
                          {[1,2,3,4,5].map(star => (
                              <button key={star} type="button" onClick={() => handleInputChange(field.id, star)} className={`text-2xl transition-transform hover:scale-110 ${formData[field.id] >= star ? 'text-yellow-400' : 'text-gray-300'}`}>★</button>
                          ))}
                      </div>
                  </div>
              );

          default: // Fallback for standard text/select
              return (
                  <div className={`${colSpan} ${anim}`}>
                      <label className="block font-bold text-gray-800 mb-1.5">{field.label} {field.required && <span className="text-red-600">*</span>}</label>
                      {field.type === 'textarea' ? (
                          <textarea className="w-full p-3 border border-gray-300 rounded-xl focus:ring-primary focus:border-primary bg-white text-gray-900" rows={3} onChange={e => handleInputChange(field.id, e.target.value)} placeholder={field.placeholder}></textarea>
                      ) : field.type === 'select' ? (
                          <select className="w-full p-3 border border-gray-300 rounded-xl focus:ring-primary focus:border-primary bg-white text-gray-900">
                              <option>اختر...</option>
                              {field.options?.map(o => <option key={o}>{o}</option>)}
                          </select>
                      ) : (
                          <input 
                            type={field.type === 'date' ? 'date' : field.type === 'time' ? 'time' : 'text'} 
                            className="w-full p-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-primary focus:border-primary transition-all bg-white text-gray-900 placeholder-gray-400"
                            placeholder={field.placeholder}
                            onChange={e => handleInputChange(field.id, e.target.value)}
                          />
                      )}
                  </div>
              );
      }
  };

  return (
    <div className="max-w-5xl mx-auto space-y-6 pb-20">
       <div className="bg-white rounded-3xl shadow-lg border border-gray-100 overflow-hidden">
           {/* Header / Nav */}
           <div className="bg-gray-50 border-b border-gray-200 p-6 flex justify-between items-center">
               <h2 className="text-2xl font-bold text-gray-800">{page.title}</h2>
               {steps.length > 1 && (
                   <div className="flex items-center gap-2">
                       <span className="text-sm font-bold text-primary">خطوة {currentStep + 1} من {steps.length}</span>
                       <div className="w-24 h-2 bg-gray-200 rounded-full overflow-hidden">
                           <div className="h-full bg-primary transition-all duration-500" style={{ width: `${((currentStep + 1) / steps.length) * 100}%` }}></div>
                       </div>
                   </div>
               )}
           </div>

           {/* Content Body */}
           <div className="p-8">
               <form onSubmit={handleSubmit}>
                   <div className="grid grid-cols-1 md:grid-cols-12 gap-6">
                       {steps[currentStep].map(field => (
                           <React.Fragment key={field.id}>
                               {renderField(field)}
                           </React.Fragment>
                       ))}
                   </div>

                   {/* Footer Actions */}
                   <div className="mt-10 flex justify-between pt-6 border-t border-gray-100">
                       <button 
                           type="button" 
                           onClick={handlePrev}
                           disabled={currentStep === 0}
                           className={`px-6 py-2 rounded-lg font-bold transition-colors ${currentStep === 0 ? 'text-gray-300 cursor-not-allowed' : 'text-gray-600 hover:bg-gray-100'}`}
                       >
                           سابق
                       </button>

                       {isLastStep ? (
                           <button type="submit" className="bg-green-600 text-white px-8 py-3 rounded-xl font-bold shadow-lg hover:bg-green-700 transform hover:-translate-y-1 transition-all">
                               إرسال الطلب <i className="fas fa-check ml-2"></i>
                           </button>
                       ) : (
                           <button type="button" onClick={handleNext} className="bg-primary text-white px-8 py-3 rounded-xl font-bold shadow-md hover:bg-primary-dark transition-colors">
                               التالي <i className="fas fa-chevron-left ml-2"></i>
                           </button>
                       )}
                   </div>
               </form>
           </div>
       </div>
    </div>
  );
};
