'use client';

import { StatsSectionProps, AboutStatItem } from '@/lib/page-builder/types';
import { EditorProps } from '@/lib/page-builder/types';
import { useState } from 'react';

const availableIcons = [
  { value: 'Users', label: '👥 Users / Clients' },
  { value: 'Calendar', label: '📅 Calendar / Experience' },
  { value: 'FileText', label: '📄 File / Posts' },
  { value: 'TrendingUp', label: '📈 Trending / Growth' },
  { value: 'Award', label: '🏆 Award / Recognition' },
  { value: 'Globe', label: '🌍 Globe / Worldwide' },
  { value: 'Clock', label: '⏰ Clock / Time' },
  { value: 'Briefcase', label: '💼 Briefcase / Projects' },
];

export default function StatsSectionEditor({ props, onUpdate }: EditorProps<StatsSectionProps>) {
  const [newStat, setNewStat] = useState<Omit<AboutStatItem, 'id'>>({
    value: 0,
    suffix: '+',
    label: '',
    icon: 'TrendingUp',
    description: ''
  });

  const handleChange = (field: keyof StatsSectionProps, value: unknown) => {
    onUpdate({ ...props, [field]: value });
  };

  const addStat = () => {
    if (newStat.label.trim() && newStat.value > 0) {
      const updatedStats = [...(props.stats || []), { 
        ...newStat, 
        id: Date.now().toString() 
      }];
      handleChange('stats', updatedStats);
      setNewStat({
        value: 0,
        suffix: '+',
        label: '',
        icon: 'TrendingUp',
        description: ''
      });
    }
  };

  const updateStat = (index: number, field: keyof AboutStatItem, value: unknown) => {
    const updatedStats = [...(props.stats || [])];
    updatedStats[index] = { ...updatedStats[index], [field]: value };
    handleChange('stats', updatedStats);
  };

  const removeStat = (index: number) => {
    const updatedStats = props.stats?.filter((_, i) => i !== index) || [];
    handleChange('stats', updatedStats);
  };

  const moveStat = (index: number, direction: 'up' | 'down') => {
    if (!props.stats) return;
    const updatedStats = [...props.stats];
    if (direction === 'up' && index > 0) {
      [updatedStats[index], updatedStats[index - 1]] = [updatedStats[index - 1], updatedStats[index]];
    } else if (direction === 'down' && index < updatedStats.length - 1) {
      [updatedStats[index], updatedStats[index + 1]] = [updatedStats[index + 1], updatedStats[index]];
    }
    handleChange('stats', updatedStats);
  };

  return (
    <div className="space-y-6 max-h-[70vh] overflow-y-auto p-1">
      <h4 className="font-semibold text-lg text-var-text border-b border-var-border pb-2">
        📊 Statistics Counter Section
      </h4>

      {/* Help Tip */}
      <div className="bg-blue-50 border border-blue-200 rounded-lg p-3 text-sm text-blue-800">
        <strong>💡 Tip:</strong> Yeh section aapke business ke important numbers dikhata hai. Visitor jab scroll karega to numbers apne aap count honay lagain gay!
      </div>

      {/* Section Title */}
      <div>
        <label className="block text-sm font-medium text-var-text mb-2">Section Title</label>
        <input
          type="text"
          value={props.title || 'Our Impact in Numbers'}
          onChange={(e) => handleChange('title', e.target.value)}
          className="w-full p-2 bg-var-input border border-var-border rounded text-var-text focus:ring-2 focus:ring-var-primary focus:border-var-primary"
          placeholder="e.g., Our Impact in Numbers"
        />
      </div>

      {/* Highlighted Text (Gradient Word) */}
      <div>
        <label className="block text-sm font-medium text-var-text mb-2">
          🌈 Highlighted Word (Gradient Mein Dikhe Ga)
        </label>
        <input
          type="text"
          value={props.highlightedText || ''}
          onChange={(e) => handleChange('highlightedText', e.target.value)}
          className="w-full p-2 bg-var-input border border-var-border rounded text-var-text focus:ring-2 focus:ring-var-primary focus:border-var-primary"
          placeholder="e.g., Impact, Numbers, Results"
        />
        <p className="text-xs text-var-text-muted mt-1">
          Example: Agar title `Our Impact in Numbers` hai aur aap `Impact` likhenge to sirf `Impact` gradient color mein aayega
        </p>
      </div>

      {/* Description */}
      <div>
        <label className="block text-sm font-medium text-var-text mb-2">Description (Optional)</label>
        <textarea
          value={props.description || ''}
          onChange={(e) => handleChange('description', e.target.value)}
          className="w-full p-2 bg-var-input border border-var-border rounded text-var-text focus:ring-2 focus:ring-var-primary focus:border-var-primary"
          rows={2}
          placeholder="e.g., Real results that speak for themselves"
        />
      </div>

      {/* Columns Selection */}
      <div>
        <label className="block text-sm font-medium text-var-text mb-2">Number of Columns</label>
        <select
          value={props.columns || 4}
          onChange={(e) => handleChange('columns', parseInt(e.target.value))}
          className="w-full p-2 bg-var-input border border-var-border rounded text-var-text focus:ring-2 focus:ring-var-primary focus:border-var-primary"
        >
          <option value={2}>2 Columns</option>
          <option value={3}>3 Columns</option>
          <option value={4}>4 Columns</option>
        </select>
        <p className="text-xs text-var-text-muted mt-1">
          Mobile pe automatically 2 columns ho jayenge
        </p>
      </div>

      {/* Animation Duration Slider */}
      <div>
        <label className="block text-sm font-medium text-var-text mb-2">
          ⏱️ Animation Speed: {props.animationDuration || 2000}ms
        </label>
        <input
          type="range"
          min="500"
          max="4000"
          step="100"
          value={props.animationDuration || 2000}
          onChange={(e) => handleChange('animationDuration', parseInt(e.target.value))}
          className="w-full"
        />
        <div className="flex justify-between text-xs text-var-text-muted mt-1">
          <span>Fast (500ms)</span>
          <span>Normal (2000ms)</span>
          <span>Slow (4000ms)</span>
        </div>
      </div>

      {/* Show Border Toggle */}
      <div className="flex items-center gap-2 py-2">
        <input
          type="checkbox"
          id="showBorder"
          checked={props.showBorder !== false}
          onChange={(e) => handleChange('showBorder', e.target.checked)}
          className="w-4 h-4 text-var-primary rounded focus:ring-var-primary"
        />
        <label htmlFor="showBorder" className="text-sm font-medium text-var-text">
          🎴 Show Card Border & Shadow
        </label>
      </div>

      {/* Statistics Items */}
      <div className="space-y-4">
        <h5 className="font-semibold text-var-text border-t border-var-border pt-4">
          📈 Statistics Items
        </h5>
        
        {/* Add New Stat Form */}
        <div className="border border-var-border rounded-lg p-4 space-y-3 bg-var-surface">
          <h6 className="font-medium text-var-text">➕ Add New Statistic</h6>
          
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-var-text-muted mb-1">Icon</label>
              <select
                value={newStat.icon}
                onChange={(e) => setNewStat({...newStat, icon: e.target.value})}
                className="w-full p-2 bg-var-input border border-var-border rounded text-sm text-var-text"
              >
                {availableIcons.map((icon) => (
                  <option key={icon.value} value={icon.value}>{icon.label}</option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-xs font-medium text-var-text-muted mb-1">Value (Number)</label>
              <input
                type="number"
                value={newStat.value}
                onChange={(e) => setNewStat({...newStat, value: parseInt(e.target.value) || 0})}
                className="w-full p-2 bg-var-input border border-var-border rounded text-sm text-var-text"
                placeholder="e.g., 500"
              />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-var-text-muted mb-1">Suffix (+, %, K, M)</label>
              <input
                type="text"
                value={newStat.suffix}
                onChange={(e) => setNewStat({...newStat, suffix: e.target.value})}
                className="w-full p-2 bg-var-input border border-var-border rounded text-sm text-var-text"
                placeholder="e.g., +, %, K"
              />
            </div>

            <div>
              <label className="block text-xs font-medium text-var-text-muted mb-1">Label</label>
              <input
                type="text"
                value={newStat.label}
                onChange={(e) => setNewStat({...newStat, label: e.target.value})}
                className="w-full p-2 bg-var-input border border-var-border rounded text-sm text-var-text"
                placeholder="e.g., Happy Clients"
              />
            </div>
          </div>

          <div>
            <label className="block text-xs font-medium text-var-text-muted mb-1">Description (Optional)</label>
            <input
              type="text"
              value={newStat.description || ''}
              onChange={(e) => setNewStat({...newStat, description: e.target.value})}
              className="w-full p-2 bg-var-input border border-var-border rounded text-sm text-var-text"
              placeholder="e.g., From 50+ countries"
            />
          </div>

          <button
            onClick={addStat}
            disabled={!newStat.label.trim() || newStat.value === 0}
            className="w-full bg-var-primary text-white py-2 rounded text-sm hover:bg-blue-700 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors"
          >
            Add Statistic
          </button>
        </div>

        {/* Existing Stats List */}
        {props.stats && props.stats.length > 0 ? (
          <div className="space-y-3">
            <div className="flex justify-between items-center">
              <label className="text-sm font-medium text-var-text">Existing Statistics ({props.stats.length})</label>
              <button
                onClick={() => handleChange('stats', [])}
                className="text-xs text-red-500 hover:text-red-700"
              >
                Clear All
              </button>
            </div>
            
            {props.stats.map((stat, index) => (
              <div key={stat.id} className="border border-var-border rounded-lg p-3 bg-var-surface">
                <div className="flex justify-between items-start mb-3">
                  <span className="font-medium text-var-text text-sm">
                    #{index + 1} {stat.label}
                  </span>
                  <div className="flex gap-1">
                    <button
                      onClick={() => moveStat(index, 'up')}
                      disabled={index === 0}
                      className="px-2 py-1 text-xs bg-gray-100 rounded hover:bg-gray-200 disabled:opacity-50"
                    >
                      ↑
                    </button>
                    <button
                      onClick={() => moveStat(index, 'down')}
                      disabled={index === (props.stats?.length || 0) - 1}
                      className="px-2 py-1 text-xs bg-gray-100 rounded hover:bg-gray-200 disabled:opacity-50"
                    >
                      ↓
                    </button>
                    <button
                      onClick={() => removeStat(index)}
                      className="px-2 py-1 text-xs bg-red-100 text-red-600 rounded hover:bg-red-200"
                    >
                      ✕
                    </button>
                  </div>
                </div>
                
                <div className="grid grid-cols-2 gap-2 text-sm">
                  <div>
                    <label className="block text-xs text-var-text-muted">Icon</label>
                    <select
                      value={stat.icon}
                      onChange={(e) => updateStat(index, 'icon', e.target.value)}
                      className="w-full p-1.5 bg-var-input border border-var-border rounded text-sm"
                    >
                      {availableIcons.map((icon) => (
                        <option key={icon.value} value={icon.value}>{icon.label}</option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="block text-xs text-var-text-muted">Value</label>
                    <input
                      type="number"
                      value={stat.value}
                      onChange={(e) => updateStat(index, 'value', parseInt(e.target.value) || 0)}
                      className="w-full p-1.5 bg-var-input border border-var-border rounded"
                    />
                  </div>
                  <div>
                    <label className="block text-xs text-var-text-muted">Suffix</label>
                    <input
                      type="text"
                      value={stat.suffix}
                      onChange={(e) => updateStat(index, 'suffix', e.target.value)}
                      className="w-full p-1.5 bg-var-input border border-var-border rounded"
                    />
                  </div>
                  <div>
                    <label className="block text-xs text-var-text-muted">Label</label>
                    <input
                      type="text"
                      value={stat.label}
                      onChange={(e) => updateStat(index, 'label', e.target.value)}
                      className="w-full p-1.5 bg-var-input border border-var-border rounded"
                    />
                  </div>
                </div>
                
                <div className="mt-2">
                  <label className="block text-xs text-var-text-muted">Description (Optional)</label>
                  <input
                    type="text"
                    value={stat.description || ''}
                    onChange={(e) => updateStat(index, 'description', e.target.value)}
                    className="w-full p-1.5 bg-var-input border border-var-border rounded text-sm mt-1"
                    placeholder="Additional info"
                  />
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="text-center py-8 bg-gray-50 rounded-lg border border-dashed border-gray-300">
            <p className="text-var-text-muted">No statistics added yet.</p>
            <p className="text-xs text-var-text-muted mt-1">Click `Add Statistic` to get started</p>
          </div>
        )}
      </div>

      {/* Preview Examples */}
      <div className="bg-gray-50 border border-gray-200 rounded-lg p-3 text-sm">
        <div className="font-medium text-var-text mb-2">📋 Example Statistics (Guest Posting Agency):</div>
        <ul className="space-y-1 text-var-text-muted text-xs">
          <li>• <strong>5+</strong> Years of Experience</li>
          <li>• <strong>500+</strong> Happy Clients</li>
          <li>• <strong>2,500+</strong> Guest Posts Delivered</li>
          <li>• <strong>98%</strong> Client Satisfaction</li>
          <li>• <strong>100+</strong> Premium Websites</li>
          <li>• <strong>50+</strong> Countries Served</li>
        </ul>
        <div className="mt-2 pt-2 border-t border-gray-200">
          <p className="text-xs text-var-text-muted">
            💡 <strong>Tip:</strong> Large numbers ke liye `K` (Thousand) ya `M` (Million) suffix use karein
          </p>
        </div>
      </div>

      {/* Shortcode Preview */}
      <div className="bg-gray-900 rounded-lg p-3">
        <p className="text-xs text-gray-400 mb-1">Preview (How it will look):</p>
        <div className="flex justify-around items-center gap-2">
          {props.stats && props.stats.slice(0, 3).map((stat, i) => (
            <div key={i} className="text-center">
              <div className="text-white text-lg font-bold">
                {stat.value}{stat.suffix}
              </div>
              <div className="text-gray-400 text-[10px]">{stat.label}</div>
            </div>
          ))}
          {(!props.stats || props.stats.length === 0) && (
            <div className="text-gray-400 text-xs">Add stats to see preview</div>
          )}
        </div>
      </div>
    </div>
  );
}