// components/organisms/ScholarshipDetail.jsx
'use client';

import { useState } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import ScholarshipApplicationModal from './ScholarshipApplicationModal';
import ScholarshipComments from "./ScholarshipComments";
import TextDisplay from '../clientcomponents/TextDisplay';

// Helper functions
const formatDate = (dateString) => {
  if (!dateString) return 'Not specified';
  const date = new Date(dateString);
  return date.toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });
};

const getDaysRemaining = (deadline) => {
  if (!deadline) return { text: 'No deadline', color: 'bg-gray-500', status: 'unknown' };
  
  const now = new Date();
  const deadlineDate = new Date(deadline);
  const diffTime = deadlineDate.getTime() - now.getTime();
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  
  if (diffDays < 0) return { text: 'Expired', color: 'bg-red-500', status: 'expired' };
  if (diffDays === 0) return { text: 'Due Today', color: 'bg-orange-500', status: 'urgent' };
  if (diffDays <= 7) return { text: `${diffDays} days left`, color: 'bg-orange-500', status: 'urgent' };
  if (diffDays <= 30) return { text: `${diffDays} days left`, color: 'bg-yellow-500', status: 'warning' };
  return { text: `${diffDays} days left`, color: 'bg-green-500', status: 'active' };
};

const formatAmountRange = (amount_min, amount_max, currency_symbol = '$') => {
  if (!amount_min && !amount_max) return 'Not specified';
  
  const symbol = currency_symbol || '$';
  
  if (amount_min && amount_max) {
    return `${symbol}${amount_min} - ${symbol}${amount_max}`;
  }
  
  if (amount_min && !amount_max) {
    return `${symbol}${amount_min}+`;
  }
  
  if (!amount_min && amount_max) {
    return `Up to ${symbol}${amount_max}`;
  }
  
  return 'Not specified';
};

const formatPercentage = (percentage) => {
  if (!percentage) return 'Not specified';
  return `${percentage}%`;
};

// Format qualifications display
const formatQualifications = (qualifications) => {
  if (!qualifications || qualifications.length === 0) {
    return 'Not specified';
  }
  
  if (qualifications.length === 1) {
    return qualifications[0].qualification_name;
  }
  
  // Show first 2 qualifications and count of remaining
  const firstTwo = qualifications.map(q => q.qualification_name).join(', ');
  
  return firstTwo;
};

const ScholarshipDetail = ({ scholarshipData, params }) => {
  const [isApplicationModalOpen, setIsApplicationModalOpen] = useState(false);

  const { scholarship, relatedScholarships = [] } = scholarshipData;
  const deadlineInfo = getDaysRemaining(scholarship.deadline);

  // Update the Apply Now handler to open the modal
  const handleApplyNow = () => {
    setIsApplicationModalOpen(true);
  };

  // Handle successful application submission
  const handleApplicationSuccess = () => {
    console.log('Application submitted successfully for scholarship:', scholarship.id);
    // You can add any post-submission logic here
  };

  // Calculate scholarship coverage details
  const getCoverageDetails = () => {
    const coverage = scholarship.percentage_cover;
    if (!coverage) return { label: 'Not specified', description: 'Coverage details not available' };
    
    if (coverage === 100) {
      return { 
        label: 'Full Scholarship', 
        description: 'Covers tuition & living expenses' 
      };
    } else if (coverage >= 75) {
      return { 
        label: 'Majority Covered', 
        description: `Covers ${coverage}% of expenses` 
      };
    } else if (coverage >= 50) {
      return { 
        label: 'Partial Scholarship', 
        description: `Covers ${coverage}% of expenses` 
      };
    } else {
      return { 
        label: 'Partial Support', 
        description: `Covers ${coverage}% of expenses` 
      };
    }
  };

  const coverageDetails = getCoverageDetails();

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-50">
      {/* Main Content */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Left Column - Main Content */}
          <div className="lg:col-span-2 space-y-8">
            {/* Hero Section */}
            <div className="bg-white rounded-2xl shadow-lg overflow-hidden">
              <div className="relative h-80">
                <Image
                  src={`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${scholarship.image}` || 'https://images.unsplash.com/photo-1523050854058-8df90110c9f1?ixlib=rb-4.0.3&w=1200'}
                  alt={scholarship.title || "Scholarship"}
                  fill
                  className="object-contain"
                  priority
                />
                <div className="absolute inset-0 bg-gradient-to-t from-black/50 to-transparent"></div>
                
                {/* Deadline Badge */}
                {scholarship.deadline && (
                  <div className="absolute top-6 right-6">
                    <div className={`px-4 py-2 rounded-full text-white font-semibold ${deadlineInfo.color} shadow-lg`}>
                      {deadlineInfo.text}
                    </div>
                  </div>
                )}

                {/* Amount Badge */}
                {(scholarship.amount_min || scholarship.amount_max) && (
                  <div className="absolute top-6 left-6">
                    <div className="px-4 py-2 rounded-full bg-green-500 text-white font-semibold shadow-lg">
                      {formatAmountRange(scholarship.amount_min, scholarship.amount_max, scholarship.currency_symbol)}
                    </div>
                  </div>
                )}

                {/* Back Button */}
                <Link 
                  href="/scholarships"
                  className="absolute bottom-6 left-6 bg-white/90 backdrop-blur-sm rounded-full p-3 hover:bg-white transition-colors shadow-lg"
                >
                  <svg className="w-5 h-5 text-gray-700" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                  </svg>
                </Link>
              </div>

              <div className="p-8">
                <div className="flex items-center justify-between mb-6">
                  <div>
                    <h1 className="text-3xl font-bold text-gray-900 mb-2">{scholarship.title}</h1>
                    <div className="flex items-center space-x-4 text-gray-600">
                      <div className="flex items-center space-x-1">
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                        </svg>
                        <span>{scholarship.country_name || 'Not specified'}</span>
                      </div>
                      <div className="flex items-center space-x-1">
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 14l9-5-9-5-9 5 9 5z" />
                        </svg>
                        <span title={formatQualifications(scholarship.qualifications)}>
                          {formatQualifications(scholarship.qualifications)}
                        </span>
                      </div>
                    </div>
                  </div>
                  
                  <div className="text-right">
                    <div className="text-2xl font-bold text-[#0B6F78]">{coverageDetails.label}</div>
                    <div className="text-sm text-gray-500">{coverageDetails.description}</div>
                  </div>
                </div>

                {/* Quick Stats */}
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
                  {/* Amount */}
                  <div className="bg-blue-50 rounded-lg p-4 text-center">
                    <div className="text-xl font-bold text-[#0B6F78]">
                      {formatAmountRange(scholarship.amount_min, scholarship.amount_max, scholarship.currency_symbol)}
                    </div>
                    <div className="text-sm text-gray-600">Scholarship Value</div>
                  </div>
                  
                  {/* Coverage */}
                  <div className="bg-green-50 rounded-lg p-4 text-center">
                    <div className="text-2xl font-bold text-green-600">
                      {formatPercentage(scholarship.percentage_cover)}
                    </div>
                    <div className="text-sm text-gray-600">Expenses Covered</div>
                  </div>
                  
                  {/* CGPA Requirement */}
                  <div className="bg-purple-50 rounded-lg p-4 text-center">
                    <div className="text-2xl font-bold text-purple-600">
                      {scholarship.cgpa || 'N/A'}
                    </div>
                    <div className="text-sm text-gray-600">Minimum CGPA</div>
                  </div>
                  
                  {/* IELTS Requirement */}
                  <div className="bg-orange-50 rounded-lg p-4 text-center">
                    <div className="text-2xl font-bold text-orange-600">
                      {scholarship.ielts ? 'Required' : 'Not Required'}
                    </div>
                    <div className="text-sm text-gray-600">IELTS</div>
                  </div>
                </div>
              </div>
            </div>

            {/* Description Section */}
            <div className="bg-white rounded-2xl shadow-lg p-8">
              
              <TextDisplay 
                  content={scholarship.description} 
                  className="prose prose-lg max-w-none text-gray-700 sn-content"
                />
            </div>

            {/* Eligibility Criteria */}
            <div className="bg-white rounded-2xl shadow-lg p-8">
              <h2 className="text-2xl font-bold text-gray-900 mb-6">Eligibility Criteria</h2>
              <div className="space-y-4">
                {/* Academic Requirements */}
                <div className="flex items-start space-x-3">
                  <svg className="w-5 h-5 text-green-500 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  <div>
                    <h3 className="font-semibold text-gray-900">Academic Requirements</h3>
                    <p className="text-gray-600">
                      Minimum CGPA: {scholarship.cgpa || 'Not specified'}
                    </p>
                  </div>
                </div>

                {/* English Proficiency */}
                <div className="flex items-start space-x-3">
                  <svg className="w-5 h-5 text-green-500 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  <div>
                    <h3 className="font-semibold text-gray-900">English Proficiency</h3>
                    <p className="text-gray-600">
                      IELTS Required: {scholarship.ielts ? 'Yes' : 'No'}
                    </p>
                  </div>
                </div>

                {/* Study Level */}
                <div className="flex items-start space-x-3">
                  <svg className="w-5 h-5 text-green-500 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 01118 0z" />
                  </svg>
                  <div>
                    <h3 className="font-semibold text-gray-900">Study Level</h3>
                    <p className="text-gray-600" title={formatQualifications(scholarship.qualifications)}>
                      {formatQualifications(scholarship.qualifications)}
                    </p>
                  </div>
                </div>

                {/* Destination Country */}
                <div className="flex items-start space-x-3">
                  <svg className="w-5 h-5 text-green-500 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  <div>
                    <h3 className="font-semibold text-gray-900">Destination Country</h3>
                    <p className="text-gray-600">
                      {scholarship.country_name || 'Not specified'}
                    </p>
                  </div>
                </div>
              </div>
            </div>

            {/* Application Process */}
            <div className="bg-white rounded-2xl shadow-lg p-8">
              <h2 className="text-2xl font-bold text-gray-900 mb-6">Application Process</h2>
              <div className="space-y-6">
                <div className="flex items-start space-x-4">
                  <div className="w-8 h-8 bg-[#0B6F78] rounded-full flex items-center justify-center text-white font-bold flex-shrink-0">1</div>
                  <div>
                    <h3 className="font-semibold text-gray-900 mb-2">Prepare Documents</h3>
                    <p className="text-gray-600">Gather academic transcripts, recommendation letters, and statement of purpose</p>
                  </div>
                </div>
                <div className="flex items-start space-x-4">
                  <div className="w-8 h-8 bg-[#0B6F78] rounded-full flex items-center justify-center text-white font-bold flex-shrink-0">2</div>
                  <div>
                    <h3 className="font-semibold text-gray-900 mb-2">Online Application</h3>
                    <p className="text-gray-600">Complete the online application form with all required information</p>
                  </div>
                </div>
                <div className="flex items-start space-x-4">
                  <div className="w-8 h-8 bg-[#0B6F78] rounded-full flex items-center justify-center text-white font-bold flex-shrink-0">3</div>
                  <div>
                    <h3 className="font-semibold text-gray-900 mb-2">Interview</h3>
                    <p className="text-gray-600">Shortlisted candidates will be invited for a virtual interview</p>
                  </div>
                </div>
                <div className="flex items-start space-x-4">
                  <div className="w-8 h-8 bg-[#0B6F78] rounded-full flex items-center justify-center text-white font-bold flex-shrink-0">4</div>
                  <div>
                    <h3 className="font-semibold text-gray-900 mb-2">Final Decision</h3>
                    <p className="text-gray-600">Receive scholarship decision within 4-6 weeks after application deadline</p>
                  </div>
                </div>
              </div>
            </div>
            <div className="bg-white rounded-2xl shadow-lg p-8">
              <ScholarshipComments scholarshipId={scholarship.id} />
            </div>
          </div>

          {/* Right Column - Sidebar */}
          <div className="space-y-6">
            {/* Application Card */}
            <div className="bg-white rounded-2xl shadow-lg p-6 sticky top-6">
              <div className="text-center mb-6">
                <div className="w-16 h-16 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] rounded-full flex items-center justify-center mx-auto mb-3">
                  <svg className="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                </div>
                <h3 className="text-xl font-bold text-gray-900">Ready to Apply?</h3>
                <p className="text-gray-600 mt-2">Don't miss this opportunity</p>
              </div>

              <div className="space-y-4 mb-6">
                <div className="flex justify-between items-center py-2 border-b border-gray-100">
                  <span className="text-gray-600">Deadline</span>
                  <span className="font-semibold text-gray-900">
                    {scholarship.deadline ? formatDate(scholarship.deadline) : 'Rolling'}
                  </span>
                </div>
                <div className="flex justify-between items-center py-2 border-b border-gray-100">
                  <span className="text-gray-600">Status</span>
                  <span className={`font-semibold ${
                    deadlineInfo.status === 'expired' ? 'text-red-600' :
                    deadlineInfo.status === 'urgent' ? 'text-orange-600' :
                    deadlineInfo.status === 'unknown' ? 'text-gray-600' :
                    'text-green-600'
                  }`}>
                    {deadlineInfo.text}
                  </span>
                </div>
                <div className="flex justify-between items-center py-2 border-b border-gray-100">
                  <span className="text-gray-600">Country</span>
                  <span className="font-semibold text-gray-900">
                    {scholarship.country_name || 'Not specified'}
                  </span>
                </div>
                <div className="flex justify-between items-center py-2 border-b border-gray-100">
                  <span className="text-gray-600">Level</span>
                  <span className="font-semibold text-gray-900" title={formatQualifications(scholarship.qualifications)}>
                    {formatQualifications(scholarship.qualifications)}
                  </span>
                </div>
                <div className="flex justify-between items-center py-2 border-b border-gray-100">
                  <span className="text-gray-600">Amount</span>
                  <span className="font-semibold text-gray-900">
                    {formatAmountRange(scholarship.amount_min, scholarship.amount_max, scholarship.currency_symbol)}
                  </span>
                </div>
                <div className="flex justify-between items-center py-2">
                  <span className="text-gray-600">Coverage</span>
                  <span className="font-semibold text-gray-900">
                    {formatPercentage(scholarship.percentage_cover)}
                  </span>
                </div>
              </div>

              <button 
                onClick={handleApplyNow}
                className="w-full bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white py-4 rounded-xl font-semibold hover:shadow-lg transition-all duration-300 transform hover:-translate-y-1 mb-3"
              >
                Apply Now
              </button>

            </div>
          </div>
        </div>

        {/* Related Scholarships */}
        {relatedScholarships.length > 0 && (
          <div className="mt-16">
            <div className="flex items-center justify-between mb-8">
              <h2 className="text-2xl font-bold text-gray-900">Related Scholarships</h2>
              <Link href="/scholarships" className="text-[#0B6F78] hover:text-[#0a306b] font-semibold">
                View All →
              </Link>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              {relatedScholarships.map((relatedScholarship) => (
                <Link 
                  key={relatedScholarship.id} 
                  href={`/scholarships/${relatedScholarship.slug}`}
                  className="bg-white rounded-2xl shadow-lg overflow-hidden hover:shadow-xl transition-shadow duration-300 block"
                >
                  <div className="relative h-40">
                    <Image
                      src={`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${relatedScholarship.image}` || 'https://images.unsplash.com/photo-1523050854058-8df90110c9f1?ixlib=rb-4.0.3&w=1200'}
                      alt={relatedScholarship.title || "Scholarship"}
                      fill
                      className="object-contain"
                    />
                    <div className="absolute top-3 right-3">
                      <div className="px-2 py-1 bg-green-500 text-white text-xs font-semibold rounded">
                        {formatAmountRange(relatedScholarship.amount_min, relatedScholarship.amount_max, relatedScholarship.currency_symbol)}
                      </div>
                    </div>
                  </div>
                  <div className="p-4">
                    <h3 className="font-semibold text-gray-900 mb-2 line-clamp-2">{relatedScholarship.title}</h3>
                    <div className="flex items-center justify-between text-sm text-gray-600">
                      <span>{relatedScholarship.country_name}</span>
                      <span>{relatedScholarship.cgpa ? `CGPA: ${relatedScholarship.cgpa}` : 'No CGPA'}</span>
                    </div>
                    <div className="mt-2 text-xs text-gray-500" title={formatQualifications(relatedScholarship.qualifications)}>
                      {formatQualifications(relatedScholarship.qualifications)}
                    </div>
                  </div>
                </Link>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Scholarship Application Modal */}
      <ScholarshipApplicationModal
        isOpen={isApplicationModalOpen}
        onClose={() => setIsApplicationModalOpen(false)}
        onSubmitSuccess={handleApplicationSuccess}
        scholarship={scholarship}
      />
    </div>
  );
};

export default ScholarshipDetail;