import React, { useState } from 'react';
import useProjectStore from '../../store/projectStore';
import { analyzeCustomFeature } from '../../services/api';
import { FEATURE_TYPES, COMPLEXITY_LEVELS } from '../../types/project.types';

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

  const handleAnalyze = async () => {
    if (!featureDescription.trim()) {
      return;
    }

    setIsAnalyzing(true);
    setAnalysisError(null);

    try {
      // REAL AI Analysis using Claude via your backend
      const analysis = await analyzeCustomFeature(featureDescription, projectType);
      
      setAiAnalysis({
        suggested_name: analysis.feature_name || featureName,
        complexity: analysis.complexity || COMPLEXITY_LEVELS.MEDIUM,
        implementation_details: analysis.implementation_details || [],
        technical_requirements: analysis.technical_requirements || [],
        estimated_effort: analysis.estimated_effort || 'Medium',
        dependencies: analysis.dependencies || [],
        api_endpoints: analysis.api_endpoints || [],
        database_tables: analysis.database_tables || [],
        confidence_score: analysis.confidence_score || 0.8
      });
    } catch (error) {
      setAnalysisError(error.message);
    } finally {
      setIsAnalyzing(false);
    }
  };

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

    const customFeature = {
      id: `ai_analyzed_${Date.now()}`,
      name: aiAnalysis.suggested_name || featureName.trim(),
      description: featureDescription.trim(),
      type: FEATURE_TYPES.CUSTOM,
      complexity: aiAnalysis.complexity,
      order: 0,
      ai_analysis: aiAnalysis,
      aiAnalyzed: true,
      implementation_details: aiAnalysis.implementation_details,
      technical_requirements: aiAnalysis.technical_requirements
    };

    addFeature(customFeature);
    onClose();
  };

  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-2xl w-full max-h-[90vh] overflow-y-auto">
        <div className="p-6">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg 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">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Feature Name (Optional - AI will suggest)
              </label>
              <input
                type="text"
                value={featureName}
                onChange={(e) => setFeatureName(e.target.value)}
                placeholder="e.g., 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"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Describe Your Feature Requirements
              </label>
              <textarea
                value={featureDescription}
                onChange={(e) => setFeatureDescription(e.target.value)}
                placeholder="Describe what this feature should do. For example: 'I want to integrate with Retell AI to make automated calls to patients for medication reminders. The system should schedule calls, track call history, show recordings, and allow custom scripts for different types of calls.'"
                rows={4}
                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
              />
              <p className="text-sm text-gray-500 mt-1">
                Be as detailed as possible. The AI will analyze and break down your requirements.
              </p>
            </div>

            {/* AI Analysis Button */}
            {!aiAnalysis && featureDescription.trim() && (
              <button
                type="button"
                onClick={handleAnalyze}
                disabled={isAnalyzing}
                className={`w-full py-3 px-4 rounded-md font-medium transition-colors ${
                  isAnalyzing
                    ? 'bg-blue-100 text-blue-600 cursor-wait'
                    : 'bg-blue-600 text-white hover:bg-blue-700'
                }`}
              >
                {isAnalyzing ? (
                  <div className="flex items-center justify-center space-x-2">
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"></div>
                    <span>🧠 AI is analyzing your feature...</span>
                  </div>
                ) : (
                  '🤖 Analyze with AI'
                )}
              </button>
            )}

            {/* 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={handleAnalyze}
                  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-2">
                      AI Analysis Complete (Confidence: {Math.round(aiAnalysis.confidence_score * 100)}%)
                    </h4>
                    
                    <div className="space-y-3 text-sm">
                      <div>
                        <strong className="text-green-900">Suggested Name:</strong>
                        <span className="ml-2 text-green-700">{aiAnalysis.suggested_name}</span>
                      </div>
                      
                      <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">Estimated Effort:</strong>
                        <span className="ml-2 text-green-700">{aiAnalysis.estimated_effort}</span>
                      </div>

                      {aiAnalysis.implementation_details.length > 0 && (
                        <div>
                          <strong className="text-green-900">Implementation Details:</strong>
                          <ul className="ml-4 mt-1 space-y-1">
                            {aiAnalysis.implementation_details.map((detail, index) => (
                              <li key={index} className="text-green-700 flex items-start">
                                <span className="mr-2">•</span>
                                {detail}
                              </li>
                            ))}
                          </ul>
                        </div>
                      )}

                      {aiAnalysis.api_endpoints.length > 0 && (
                        <div>
                          <strong className="text-green-900">Required API Endpoints:</strong>
                          <ul className="ml-4 mt-1 space-y-1">
                            {aiAnalysis.api_endpoints.map((endpoint, index) => (
                              <li key={index} className="text-green-700 font-mono text-xs">
                                {endpoint}
                              </li>
                            ))}
                          </ul>
                        </div>
                      )}

                      {aiAnalysis.dependencies.length > 0 && (
                        <div>
                          <strong className="text-green-900">Dependencies:</strong>
                          <div className="flex flex-wrap gap-2 mt-1">
                            {aiAnalysis.dependencies.map((dep, index) => (
                              <span key={index} className="bg-green-100 text-green-800 px-2 py-1 rounded text-xs">
                                {dep}
                              </span>
                            ))}
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            )}

            <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() || isAnalyzing}
                className={`flex-1 py-2 px-4 rounded-md font-medium transition-colors ${
                  !featureDescription.trim() || isAnalyzing
                    ? 'bg-gray-300 text-gray-500 cursor-not-allowed'
                    : 'bg-green-600 text-white hover:bg-green-700'
                }`}
              >
                {aiAnalysis ? 'Add AI-Analyzed Feature' : 'Analyze & Add Feature'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}
