import React, { useState, useEffect } from 'react';
import useProjectStore from '../../store/projectStore';
import { analyzeFeatureWithAI } from '../../services/aiAnalysis';
import { FEATURE_TYPES } from '../../types/project.types';

export default function EnhancedCustomFeatureCreator({ onClose }) {
  const [featureName, setFeatureName] = useState('');
  const [featureDescription, setFeatureDescription] = useState('');
  const [requirements, setRequirements] = useState(['']);
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [aiAnalysis, setAiAnalysis] = useState(null);
  const [logicRules, setLogicRules] = useState([]);
  const [analysisError, setAnalysisError] = useState(null);
  
  const { addFeature } = useProjectStore();

  // Add new requirement input
  const addRequirement = () => {
    setRequirements([...requirements, '']);
  };

  // Update specific requirement
  const updateRequirement = (index, value) => {
    const newRequirements = [...requirements];
    newRequirements[index] = value;
    setRequirements(newRequirements);
  };

  // Remove requirement
  const removeRequirement = (index) => {
    const newRequirements = requirements.filter((_, i) => i !== index);
    setRequirements(newRequirements.length === 0 ? [''] : newRequirements);
  };

  // Add new logic rule
  const addLogicRule = () => {
    setLogicRules([...logicRules, '']);
  };

  // Update specific logic rule
  const updateLogicRule = (index, value) => {
    const newRules = [...logicRules];
    newRules[index] = value;
    setLogicRules(newRules);
  };

  // Remove logic rule
  const removeLogicRule = (index) => {
    const newRules = logicRules.filter((_, i) => i !== index);
    setLogicRules(newRules);
  };

  // Auto-trigger AI analysis when user finishes adding requirements
  useEffect(() => {
    const validRequirements = requirements.filter(req => req.trim());
    
    if (featureName.trim() && featureDescription.trim() && validRequirements.length > 0 && !isAnalyzing && !aiAnalysis) {
      const timer = setTimeout(() => {
        handleAIAnalysis();
      }, 2000); // Wait 2 seconds after user stops typing
      
      return () => clearTimeout(timer);
    }
  }, [featureName, featureDescription, requirements]);

  const handleAIAnalysis = async () => {
    const validRequirements = requirements.filter(req => req.trim());
    
    if (!featureName.trim() || !featureDescription.trim() || validRequirements.length === 0) {
      return;
    }

    setIsAnalyzing(true);
    setAnalysisError(null);

    try {
      console.log('🚀 Starting AI analysis...');
      const analysis = await analyzeFeatureWithAI(featureName, featureDescription, validRequirements);
      
      setAiAnalysis({
        complexity: analysis.complexity,
        confidence_score: 0.9
      });

      // Set AI-generated logic rules (user can edit these)
      setLogicRules(analysis.logicRules || []);
      
      console.log('✅ AI Analysis completed:', analysis);

    } catch (error) {
      console.error('❌ AI Analysis error:', error);
      setAnalysisError(error.message);
    } finally {
      setIsAnalyzing(false);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (!aiAnalysis) {
      await handleAIAnalysis();
      return;
    }

    const validRequirements = requirements.filter(req => req.trim());
    const validLogicRules = logicRules.filter(rule => rule.trim());

    const enhancedFeature = {
      id: `enhanced_${Date.now()}`,
      name: featureName.trim(),
      description: featureDescription.trim(),
      type: FEATURE_TYPES.CUSTOM,
      complexity: aiAnalysis.complexity,
      order: 0,
      
      // Enhanced data structure for requirement processor
      featureName: featureName.trim(),
      requirements: validRequirements,
      logicRules: validLogicRules,
      aiAnalyzed: true
    };

    console.log('🚀 Adding enhanced feature:', enhancedFeature);
    addFeature(enhancedFeature);
    onClose();
  };

  const validRequirements = requirements.filter(req => req.trim());

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg shadow-xl max-w-3xl w-full max-h-[90vh] overflow-y-auto">
        <div className="p-6">
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-xl font-semibold text-gray-900">
              🚀 AI-Powered Feature Creator
            </h3>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600 transition-colors"
            >
              <span className="text-xl">×</span>
            </button>
          </div>

          <form onSubmit={handleSubmit} className="space-y-6">
            {/* Feature Name */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Feature Name
              </label>
              <input
                type="text"
                value={featureName}
                onChange={(e) => setFeatureName(e.target.value)}
                placeholder="e.g., Patient Management, Retell AI Integration"
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                required
              />
            </div>

            {/* Feature Description */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Feature Description
              </label>
              <textarea
                value={featureDescription}
                onChange={(e) => setFeatureDescription(e.target.value)}
                placeholder="Describe what this feature should do..."
                rows={3}
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                required
              />
            </div>

            {/* Requirements List */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Detailed Requirements (Add one by one)
              </label>
              <div className="space-y-3">
                {requirements.map((requirement, index) => (
                  <div key={index} className="flex items-center space-x-2">
                    <div className="flex-shrink-0 w-6 h-6 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center text-sm font-medium">
                      {index + 1}
                    </div>
                    <input
                      type="text"
                      value={requirement}
                      onChange={(e) => updateRequirement(index, e.target.value)}
                      placeholder="e.g., CRUD operations for patient records"
                      className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    />
                    {requirements.length > 1 && (
                      <button
                        type="button"
                        onClick={() => removeRequirement(index)}
                        className="w-8 h-8 bg-red-100 text-red-600 rounded hover:bg-red-200 transition-colors flex items-center justify-center"
                      >
                        ×
                      </button>
                    )}
                  </div>
                ))}
              </div>
              
              <button
                type="button"
                onClick={addRequirement}
                className="mt-3 text-blue-600 hover:text-blue-700 text-sm font-medium flex items-center space-x-1"
              >
                <span>+</span>
                <span>Add another requirement</span>
              </button>
              
              <p className="text-sm text-gray-500 mt-2">
                Add specific functional requirements. AI will analyze automatically when you're done.
              </p>
            </div>

            {/* AI Analysis Status */}
            {isAnalyzing && (
              <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
                <div className="flex items-center space-x-2">
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"></div>
                  <span className="text-blue-700 text-sm">
                    🧠 AI is analyzing your requirements... ({validRequirements.length} requirements)
                  </span>
                </div>
              </div>
            )}

            {/* Analysis Error */}
            {analysisError && (
              <div className="p-4 bg-red-50 border border-red-200 rounded-lg">
                <p className="text-red-700 text-sm">
                  <strong>Analysis Error:</strong> {analysisError}
                </p>
                <button
                  type="button"
                  onClick={handleAIAnalysis}
                  className="mt-2 text-red-600 hover:text-red-700 text-sm font-medium"
                >
                  Try Again
                </button>
              </div>
            )}

            {/* AI Analysis Results */}
            {aiAnalysis && (
              <div className="space-y-4 p-4 bg-green-50 border border-green-200 rounded-lg">
                <div className="flex items-start space-x-2">
                  <span className="text-green-600 text-lg">🧠</span>
                  <div className="flex-1">
                    <h4 className="font-medium text-green-900 mb-3">
                      AI Analysis Complete!
                    </h4>
                    
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                      <div>
                        <strong className="text-green-900">Complexity:</strong>
                        <span className={`ml-2 px-2 py-1 rounded text-xs ${
                          aiAnalysis.complexity === 'low' ? 'bg-green-100 text-green-800' :
                          aiAnalysis.complexity === 'medium' ? 'bg-yellow-100 text-yellow-800' :
                          'bg-red-100 text-red-800'
                        }`}>
                          {aiAnalysis.complexity.toUpperCase()}
                        </span>
                      </div>

                      <div>
                        <strong className="text-green-900">Requirements Analyzed:</strong>
                        <p className="text-green-700">{validRequirements.length} requirements</p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* Editable Logic Rules */}
            {aiAnalysis && (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Logic Rules (AI-generated, you can edit/add more)
                </label>
                <div className="space-y-3">
                  {logicRules.map((rule, index) => (
                    <div key={index} className="flex items-center space-x-2">
                      <div className="flex-shrink-0 w-6 h-6 bg-purple-100 text-purple-600 rounded-full flex items-center justify-center text-sm font-medium">
                        R{index + 1}
                      </div>
                      <input
                        type="text"
                        value={rule}
                        onChange={(e) => updateLogicRule(index, e.target.value)}
                        placeholder="e.g., Only caregivers can access their patients"
                        className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                      />
                      <button
                        type="button"
                        onClick={() => removeLogicRule(index)}
                        className="w-8 h-8 bg-red-100 text-red-600 rounded hover:bg-red-200 transition-colors flex items-center justify-center"
                      >
                        ×
                      </button>
                    </div>
                  ))}
                </div>
                
                <button
                  type="button"
                  onClick={addLogicRule}
                  className="mt-3 text-purple-600 hover:text-purple-700 text-sm font-medium flex items-center space-x-1"
                >
                  <span>+</span>
                  <span>Add custom logic rule</span>
                </button>
              </div>
            )}

            {/* Submit Buttons */}
            <div className="flex space-x-3 pt-4 border-t border-gray-200">
              <button
                type="button"
                onClick={onClose}
                className="flex-1 py-2 px-4 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 transition-colors"
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={!featureDescription.trim() || validRequirements.length === 0 || isAnalyzing}
                className={`flex-1 py-2 px-4 rounded-md font-medium transition-colors ${
                  !featureDescription.trim() || validRequirements.length === 0 || isAnalyzing
                    ? 'bg-gray-300 text-gray-500 cursor-not-allowed'
                    : aiAnalysis 
                    ? 'bg-green-600 text-white hover:bg-green-700'
                    : 'bg-blue-600 text-white hover:bg-blue-700'
                }`}
              >
                {isAnalyzing ? 'Analyzing...' : aiAnalysis ? 'Add AI-Analyzed Feature' : 'Analyze & Add Feature'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}
