// EligibilityCalculator.jsx
'use client';

import React, { useState } from 'react';
import { 
  GraduationCap, 
  MapPin, 
  DollarSign, 
  Award, 
  Clock,
  Globe,
  BookOpen,
  Calculator,
  ArrowRight,
  Shield,
  Sparkles,
  CheckCircle,
  User
} from 'lucide-react';

const EligibilityCalculator = ({ countries = [], levels = [], subjects = [] }) => {
  const [formData, setFormData] = useState({
    country: '',
    gpa: '',
    ielts: '',
    budget: '',
    major: '',
    qualification: ''
  });

  const [results, setResults] = useState(null);
  const [loading, setLoading] = useState(false);

  // Use the data from props instead of hardcoded arrays
  const qualifications = levels.map(level => ({
    id: level.id,
    title: level.title
  }));

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

  const calculateEligibility = async () => {
    setLoading(true);
    
    try {
      const response = await fetch('http://localhost:8000/search', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          query: `${formData.major} in ${formData.country}`,
          country: formData.country,
          qualification: formData.qualification,
          max_fee: parseFloat(formData.budget),
          limit: 5
        })
      });

      const data = await response.json();
      const chances = calculateChances(formData);
      
      setResults({
        courses: data.courses || generateMockCourses(),
        chances: chances,
        recommendations: generateRecommendations(formData, chances)
      });
    } catch (error) {
      // Fallback to mock data
      setResults({
        courses: generateMockCourses(),
        chances: calculateChances(formData),
        recommendations: generateRecommendations(formData, calculateChances(formData))
      });
    } finally {
      setLoading(false);
    }
  };

  const calculateChances = (data) => {
    let visaChance = 70, scholarshipChance = 30, admissionChance = 75;

    // GPA impact
    if (parseFloat(data.gpa) >= 3.5) {
      admissionChance += 15;
      scholarshipChance += 20;
    } else if (parseFloat(data.gpa) >= 3.0) {
      admissionChance += 5;
      scholarshipChance += 10;
    }

    // IELTS impact
    if (parseFloat(data.ielts) >= 7.5) {
      visaChance += 15;
      admissionChance += 10;
    } else if (parseFloat(data.ielts) >= 6.5) {
      visaChance += 5;
      admissionChance += 5;
    }

    // Budget impact
    if (parseFloat(data.budget) >= 30000) {
      admissionChance += 5;
    }

    return {
      visa: Math.min(95, Math.max(50, visaChance)),
      scholarship: Math.min(80, Math.max(10, scholarshipChance)),
      admission: Math.min(95, Math.max(60, admissionChance))
    };
  };

  const generateRecommendations = (data, chances) => {
    const recommendations = [];
    if (chances.visa < 75) recommendations.push('Improve IELTS score for better visa chances');
    if (chances.scholarship < 40) recommendations.push('Higher GPA increases scholarship opportunities');
    if (parseFloat(data.budget) < 20000) recommendations.push('Consider countries with lower tuition fees');
    return recommendations;
  };

  const generateMockCourses = () => [
    {
      id: 1,
      name: `${formData.qualification} in ${formData.major}`,
      university_name: 'International University',
      country_name: formData.country || 'Selected Country',
      yearly_fee: '35000',
      duration: formData.qualification === 'Bachelor\'s Degree' ? '48' : '24',
      scholarship: true,
      similarity_score: 0.92
    },
    {
      id: 2,
      name: `${formData.major} Program`,
      university_name: 'Global Institute',
      country_name: formData.country || 'Selected Country',
      yearly_fee: '28000',
      duration: formData.qualification === 'Bachelor\'s Degree' ? '36' : '18',
      scholarship: false,
      similarity_score: 0.88
    }
  ];

  const resetCalculator = () => {
    setFormData({ country: '', gpa: '', ielts: '', budget: '', major: '', qualification: '' });
    setResults(null);
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100">
      {/* Header */}
      <section className="bg-gradient-to-r from-[#0B6F78] to-[#0a306b] py-16">
        <div className="max-w-4xl mx-auto px-4 text-center">
          <div className="flex items-center justify-center gap-3 mb-4">
            <Calculator className="w-8 h-8 text-white" />
            <h1 className="text-3xl md:text-4xl font-bold text-white">
              Study Abroad Eligibility Check
            </h1>
          </div>
          <p className="text-white/80 text-lg">
            Enter your details and discover your study abroad opportunities
          </p>
        </div>
      </section>

      {/* Main Content */}
      <div className="max-w-4xl mx-auto px-4 py-8 mt-10">
        {!results ? (
          // Step 1: Input Form
          <div className="bg-white rounded-2xl shadow-xl p-6">
            <h2 className="text-2xl font-bold text-gray-900 mb-6 text-center">
              Enter Your Details
            </h2>

            <div className="grid md:grid-cols-2 gap-6">
              {/* Left Column */}
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-2">
                    <MapPin className="w-4 h-4 inline mr-2" />
                    Preferred Country
                  </label>
                  <select
                    value={formData.country}
                    onChange={(e) => handleInputChange('country', e.target.value)}
                    className="w-full p-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#0B6F78]"
                  >
                    <option value="">Select country</option>
                    {countries.map(country => (
                      <option key={country.id} value={country.country}>
                        {country.country}
                      </option>
                    ))}
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-2">
                    <GraduationCap className="w-4 h-4 inline mr-2" />
                    Current Qualification
                  </label>
                  <select
                    value={formData.qualification}
                    onChange={(e) => handleInputChange('qualification', e.target.value)}
                    className="w-full p-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#0B6F78]"
                  >
                    <option value="">Select qualification</option>
                    {qualifications.map(qual => (
                      <option key={qual.id} value={qual.title}>
                        {qual.title}
                      </option>
                    ))}
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-2">
                    <BookOpen className="w-4 h-4 inline mr-2" />
                    Field of Study
                  </label>
                  <select
                    value={formData.major}
                    onChange={(e) => handleInputChange('major', e.target.value)}
                    className="w-full p-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#0B6F78]"
                  >
                    <option value="">Select field</option>
                    {subjects.map(subject => (
                      <option key={subject.id} value={subject.name}>
                        {subject.name}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              {/* Right Column */}
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-2">
                    <User className="w-4 h-4 inline mr-2" />
                    Current GPA
                  </label>
                  <input
                    type="number"
                    step="0.1"
                    min="0"
                    max="4.0"
                    value={formData.gpa}
                    onChange={(e) => handleInputChange('gpa', e.target.value)}
                    placeholder="e.g., 3.5"
                    className="w-full p-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#0B6F78]"
                  />
                </div>

                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-2">
                    <Globe className="w-4 h-4 inline mr-2" />
                    IELTS Score
                  </label>
                  <input
                    type="number"
                    step="0.5"
                    min="0"
                    max="9"
                    value={formData.ielts}
                    onChange={(e) => handleInputChange('ielts', e.target.value)}
                    placeholder="e.g., 7.5"
                    className="w-full p-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#0B6F78]"
                  />
                </div>

                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-2">
                    <DollarSign className="w-4 h-4 inline mr-2" />
                    Annual Budget (USD)
                  </label>
                  <input
                    type="number"
                    value={formData.budget}
                    onChange={(e) => handleInputChange('budget', e.target.value)}
                    placeholder="e.g., 30000"
                    className="w-full p-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#0B6F78]"
                  />
                </div>

                <div className="pt-2">
                  <button
                    onClick={calculateEligibility}
                    disabled={!formData.country || !formData.gpa || !formData.major || !formData.qualification || loading}
                    className="w-full bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white py-3 rounded-xl font-semibold hover:shadow-lg transition-all disabled:opacity-50"
                  >
                    {loading ? (
                      <div className="flex items-center justify-center gap-2">
                        <div className="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent"></div>
                        Calculating...
                      </div>
                    ) : (
                      <>
                        Check Eligibility <ArrowRight className="w-4 h-4 inline ml-2" />
                      </>
                    )}
                  </button>
                </div>
              </div>
            </div>
          </div>
        ) : (
          // Step 2: Results (same as before)
          <div className="space-y-6">
            {/* Results Header */}
            <div className="bg-white rounded-2xl shadow-xl p-6">
              <div className="flex justify-between items-center mb-6">
                <div>
                  <h2 className="text-2xl font-bold text-gray-900">Your Results</h2>
                  <p className="text-gray-600">Based on your {formData.qualification} profile</p>
                </div>
                <button
                  onClick={resetCalculator}
                  className="px-4 py-2 bg-[#0B6F78] text-white rounded-xl font-semibold hover:bg-[#0a306b]"
                >
                  New Search
                </button>
              </div>

              {/* Chance Cards */}
              <div className="grid md:grid-cols-3 gap-4 mb-6">
                <div className="bg-green-50 border border-green-200 rounded-xl p-4 text-center">
                  <Shield className="w-6 h-6 text-green-600 mx-auto mb-2" />
                  <div className="text-2xl font-bold text-green-700">{results.chances.admission}%</div>
                  <div className="text-sm text-gray-600">Admission Chance</div>
                </div>

                <div className="bg-blue-50 border border-blue-200 rounded-xl p-4 text-center">
                  <Award className="w-6 h-6 text-blue-600 mx-auto mb-2" />
                  <div className="text-2xl font-bold text-blue-700">{results.chances.scholarship}%</div>
                  <div className="text-sm text-gray-600">Scholarship Chance</div>
                </div>

                <div className="bg-purple-50 border border-purple-200 rounded-xl p-4 text-center">
                  <Globe className="w-6 h-6 text-purple-600 mx-auto mb-2" />
                  <div className="text-2xl font-bold text-purple-700">{results.chances.visa}%</div>
                  <div className="text-sm text-gray-600">Visa Success</div>
                </div>
              </div>

              {/* Recommendations */}
              {results.recommendations.length > 0 && (
                <div className="bg-yellow-50 border border-yellow-200 rounded-xl p-4">
                  <h3 className="font-semibold text-gray-900 mb-3 flex items-center gap-2">
                    <Sparkles className="w-4 h-4 text-yellow-600" />
                    Suggestions to Improve
                  </h3>
                  <div className="space-y-2">
                    {results.recommendations.map((rec, index) => (
                      <div key={index} className="flex items-start gap-2">
                        <CheckCircle className="w-4 h-4 text-yellow-600 mt-0.5" />
                        <span className="text-sm text-gray-700">{rec}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {/* Recommended Courses */}
            <div className="bg-white rounded-2xl shadow-xl p-6">
              <h3 className="text-xl font-bold text-gray-900 mb-4">
                Recommended {formData.qualification} Programs ({results.courses.length})
              </h3>

              <div className="space-y-4">
                {results.courses.map((course) => (
                  <div key={course.id} className="border border-gray-200 rounded-xl p-4 hover:shadow-md transition-shadow">
                    <div className="flex justify-between items-start">
                      <div>
                        <h4 className="font-semibold text-gray-900">{course.name}</h4>
                        <p className="text-gray-600 text-sm">{course.university_name}</p>
                        <p className="text-gray-500 text-sm flex items-center gap-1 mt-1">
                          <MapPin className="w-3 h-3" />
                          {course.country_name}
                        </p>
                      </div>
                      <div className="text-right">
                        <div className="bg-green-100 text-green-800 px-2 py-1 rounded-full text-xs font-medium mb-1">
                          {Math.round(course.similarity_score * 100)}% Match
                        </div>
                        <div className="font-bold text-gray-900">${parseInt(course.yearly_fee).toLocaleString()}</div>
                      </div>
                    </div>

                    <div className="flex items-center justify-between text-sm text-gray-600 mt-3">
                      <div className="flex items-center gap-3">
                        <span className="flex items-center gap-1">
                          <Clock className="w-3 h-3" />
                          {course.duration} months
                        </span>
                        {course.scholarship && (
                          <span className="flex items-center gap-1 text-green-600">
                            <Award className="w-3 h-3" />
                            Scholarships
                          </span>
                        )}
                      </div>
                      <button className="text-[#0B6F78] font-semibold text-sm">
                        View Details →
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default EligibilityCalculator;