'use client';

import React, { useState, useEffect } from 'react';
import { 
  Download, 
  Search, 
  X, 
  FileText, 
  BookOpen, 
  Shield, 
  Award, 
  GraduationCap, 
  ArrowRight, 
  Users, 
  Clock, 
  Star,
  Sparkles,
  Zap,
  CheckCircle,
  FileSearch,
  FileUp,
  Info,
  Mail,
  Phone,
  User
} from 'lucide-react';
import Swal from 'sweetalert2';
import Link from "next/link";

// Import Shared Components (or use inline versions)
import ModernCard from '../../components/shared/ModernCard';
import StatCard from '../../components/shared/StatCard';
import FeatureCard from '../../components/shared/FeatureCard';
import CustomInput from '../../components/shared/CustomInput';

// Inline components if imports fail
const ModernCardInline = ({ children, className = '' }) => (
  <div className={`bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden ${className}`}>
    {children}
  </div>
);

const CustomInputInline = ({ Icon, placeholder, name, value, onChange, type = 'text' }) => (
  <div className="relative">
    {Icon && (
      <div className="absolute left-4 top-1/2 transform -translate-y-1/2">
        <Icon className="w-5 h-5 text-gray-400" />
      </div>
    )}
    <input
      type={type}
      name={name}
      placeholder={placeholder}
      value={value}
      onChange={onChange}
      className={`w-full px-4 py-3 ${Icon ? 'pl-12' : 'pl-4'} border border-gray-300 rounded-xl focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-white transition-all duration-300`}
    />
  </div>
);

const FeatureCardInline = ({ Icon, title, description, color = 'teal' }) => {
  const colorClasses = {
    teal: 'bg-teal-50 border-teal-100',
    blue: 'bg-blue-50 border-blue-100',
    emerald: 'bg-emerald-50 border-emerald-100',
    amber: 'bg-amber-50 border-amber-100'
  };

  const iconColorClasses = {
    teal: 'text-teal-600',
    blue: 'text-blue-600',
    emerald: 'text-emerald-600',
    amber: 'text-amber-600'
  };

  return (
    <div className={`rounded-2xl p-6 border ${colorClasses[color]} transition-all duration-300 hover:shadow-lg`}>
      <div className="flex items-start gap-4">
        <div className={`p-3 rounded-xl ${colorClasses[color].replace('50', '100')}`}>
          <Icon className={`w-6 h-6 ${iconColorClasses[color]}`} />
        </div>
        <div>
          <h4 className="font-bold text-gray-900 mb-2">{title}</h4>
          <p className="text-gray-600 text-sm">{description}</p>
        </div>
      </div>
    </div>
  );
};

const StatCardInline = ({ Icon, number, label, color = 'teal', className = '' }) => {
  const colorClasses = {
    teal: 'text-teal-600',
    blue: 'text-blue-600',
    emerald: 'text-emerald-600',
    amber: 'text-amber-600'
  };

  return (
    <div className={`bg-white rounded-2xl p-6 text-center shadow-lg border border-gray-100 hover:shadow-xl transition-all duration-300 ${className}`}>
      <div className={`inline-flex p-3 rounded-xl bg-linear-to-r ${color === 'teal' ? 'from-teal-50 to-blue-50' : color === 'blue' ? 'from-blue-50 to-cyan-50' : color === 'emerald' ? 'from-emerald-50 to-green-50' : 'from-amber-50 to-yellow-50'} mb-4`}>
        <Icon className={`w-8 h-8 ${colorClasses[color]}`} />
      </div>
      <div className="text-3xl font-bold text-gray-900 mb-1">{number}</div>
      <div className="text-gray-600 text-sm">{label}</div>
    </div>
  );
};

// Use either imported or inline components
const ModernCardComponent = ModernCard || ModernCardInline;
const CustomInputComponent = CustomInput || CustomInputInline;
const FeatureCardComponent = FeatureCard || FeatureCardInline;
const StatCardComponent = StatCard || StatCardInline;

export default function StudentSupportDocument() {
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedDoc, setSelectedDoc] = useState(null);
  const [formData, setFormData] = useState({ name: "", email: "", phone: "" });
  const [documents, setDocuments] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [activeCategory, setActiveCategory] = useState("all");

  useEffect(() => {
    const fetchDocs = async () => {
      setLoading(true);
      setError("");
      try {
        const res = await fetch('/api/frontend/student-support-documents');
        if (!res.ok) throw new Error('Failed to fetch documents');
        const data = await res.json();
        setDocuments(data);
      } catch (err) {
        setError('Failed to load documents.');
      }
      setLoading(false);
    };
    fetchDocs();
  }, []);

  // Extract unique categories
  const categories = ["all", ...new Set(documents.map(doc => doc.file_category || 'General'))];

  const filteredDocs = documents.filter((doc) => {
    const matchesSearch = doc.file_name.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesCategory = activeCategory === "all" || doc.file_category === activeCategory;
    return matchesSearch && matchesCategory;
  });

  const handleDownloadClick = (doc) => {
    setSelectedDoc(doc);
  };

  const validateForm = () => {
    if (!formData.name.trim() || !formData.email.trim() || !formData.phone.trim()) {
      Swal.fire({
        icon: 'error',
        title: 'Form Error',
        text: 'Please fill all required fields correctly.',
      });
      return false;
    }
    if (!/^\S+@\S+\.\S+$/.test(formData.email)) {
      Swal.fire({
        icon: 'error',
        title: 'Invalid Email',
        text: 'Please enter a valid email address.',
      });
      return false;
    }
    return true;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!validateForm()) return;

    try {
      const res = await fetch('/api/frontend/student-support-document-downloads', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...formData, documentId: selectedDoc.id }),
      });

      if (res.ok) {
        await Swal.fire({
          icon: 'success',
          title: 'Success!',
          text: 'Your details have been submitted. Your download will start shortly.',
        });

        // ✅ Download file after success
        const link = document.createElement('a');
        link.href = selectedDoc.file || selectedDoc.document_file;
        link.download = selectedDoc.title || selectedDoc.file_name;
        link.click();

        // Reset form and close modal
        setSelectedDoc(null);
        setFormData({ name: '', email: '', phone: '' });
      } else {
        throw new Error('Failed to save user info');
      }
    } catch (err) {
      console.error(err);
      Swal.fire({
        icon: 'error',
        title: 'Submission Failed',
        text: 'Please try again later.',
      });
    }
  };

  return (
    <div className="min-h-screen bg-linear-to-b from-gray-50 to-white">
      {/* Hero Section */}
      <div className="relative">
        <div className="absolute inset-0 bg-linear-to-r from-teal-50/50 to-blue-50/50"></div>
        
        <div className="absolute top-0 left-0 w-full h-full overflow-hidden">
          {[...Array(15)].map((_, i) => (
            <div
              key={i}
              className="absolute rounded-full bg-linear-to-r from-teal-200/20 to-blue-200/20 animate-float"
              style={{
                width: Math.random() * 80 + 40,
                height: Math.random() * 80 + 40,
                top: `${Math.random() * 100}%`,
                left: `${Math.random() * 100}%`,
                animationDelay: `${Math.random() * 5}s`,
                animationDuration: `${Math.random() * 10 + 10}s`
              }}
            />
          ))}
        </div>

        <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-20 md:py-28">
          <div className="text-center">
            <div className="inline-flex items-center gap-2 bg-linear-to-r from-teal-100 to-blue-100 text-teal-700 px-6 py-3 rounded-full text-sm font-semibold mb-8 animate-pulse">
              <Shield className="w-5 h-5" />
              Trusted Academic Resources
            </div>

            <h1 className="text-5xl md:text-7xl font-bold text-gray-900 mb-8 leading-tight">
              Student{' '}
              <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                Support Documents
              </span>
            </h1>

            <p className="text-xl md:text-2xl text-gray-600 mb-12 max-w-3xl mx-auto leading-relaxed">
              Access comprehensive academic resources, official forms, and essential documents 
              curated to empower your educational journey
            </p>

            {/* Search Box */}
            <ModernCardComponent className="max-w-3xl mx-auto p-8">
              <div className="flex flex-col items-center text-center gap-4 mb-8">
                <div className="p-3 rounded-xl bg-linear-to-r from-teal-50 to-blue-50 border border-teal-100">
                  <Search className="w-8 h-8 text-teal-600" />
                </div>
                <div>
                  <h2 className="text-2xl font-bold text-gray-900">Find Academic Resources</h2>
                  <p className="text-gray-600 mt-2">
                    Search documents by name, keyword, or category
                  </p>
                </div>
              </div>

              <div className="relative">
                <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                <input
                  type="text"
                  placeholder="Search documents by name, keyword, or category..."
                  className="w-full pl-12 pr-4 py-4 border border-gray-300 rounded-xl focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-white transition-all duration-300 text-lg"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
              </div>

              {/* Category Filter */}
              <div className="flex flex-wrap gap-2 mt-6 justify-center">
                {categories.map((category) => (
                  <button
                    key={category}
                    onClick={() => setActiveCategory(category)}
                    className={`px-4 py-2 rounded-full text-sm font-medium transition-all duration-300 ${
                      activeCategory === category
                        ? 'bg-linear-to-r from-teal-600 to-blue-500 text-white shadow-lg'
                        : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                    }`}
                  >
                    {category === 'all' ? 'All Categories' : category}
                  </button>
                ))}
              </div>
            </ModernCardComponent>
          </div>
        </div>
      </div>

      {/* Stats Section */}
      <div className="py-16">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-12">
            <h2 className="text-3xl font-bold text-gray-900 mb-4">
              Our Document Library
            </h2>
            <p className="text-gray-600 max-w-2xl mx-auto">
              Comprehensive collection of verified academic resources
            </p>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
            <StatCardComponent 
              Icon={FileText}
              number={`${documents.length}+`}
              label="Documents Available"
              color="teal"
            />
            <StatCardComponent 
              Icon={Users}
              number="5,000+"
              label="Monthly Downloads"
              color="blue"
            />
            <StatCardComponent 
              Icon={Clock}
              number="24/7"
              label="Access Available"
              color="emerald"
            />
            <StatCardComponent 
              Icon={Award}
              number="100%"
              label="Verified Content"
              color="amber"
            />
          </div>
        </div>
      </div>

      {/* Documents Section */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="text-center mb-12">
          <h2 className="text-3xl font-bold text-gray-900 mb-4">
            Academic Resources Collection
          </h2>
          <p className="text-gray-600 max-w-3xl mx-auto text-lg">
            Discover our carefully curated library of essential academic documents, 
            forms, and resources designed to support your educational success
          </p>
        </div>

        {loading ? (
          <ModernCardComponent className="p-12 text-center">
            <div className="inline-flex items-center justify-center mb-4">
              <div className="animate-spin rounded-full h-16 w-16 border-t-4 border-b-4 border-teal-500"></div>
            </div>
            <p className="text-gray-600 text-lg">Loading academic resources...</p>
          </ModernCardComponent>
        ) : error ? (
          <ModernCardComponent className="p-12 text-center">
            <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <X className="text-red-600" size={32} />
            </div>
            <p className="text-red-600 font-medium text-lg mb-4">{error}</p>
            <button 
              className="px-6 py-3 bg-linear-to-r from-teal-600 to-blue-500 text-white rounded-xl font-semibold hover:shadow-lg transition-all duration-300 transform hover:-translate-y-1"
              onClick={() => window.location.reload()}
            >
              Try Again
            </button>
          </ModernCardComponent>
        ) : filteredDocs.length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {filteredDocs.map((doc) => (
              <ModernCardComponent 
                key={doc.id} 
                className="group hover:shadow-2xl transition-all duration-500 overflow-hidden"
              >
                {/* Accent bar */}
                <div className="h-1 w-full bg-linear-to-r from-teal-600 to-blue-500" />

                <div className="p-6">
                  {/* Icon + Title */}
                  <div className="flex items-start gap-4 mb-5">
                    <div className="p-3 rounded-xl bg-linear-to-r from-teal-50 to-blue-50 border border-teal-100 group-hover:scale-105 transition-transform duration-300">
                      <FileText className="w-6 h-6 text-teal-600" />
                    </div>
                    <div className="flex-1">
                      <h4 className="font-bold text-gray-900 text-lg line-clamp-2 group-hover:text-teal-600 transition-colors duration-300">
                        {doc.file_name}
                      </h4>
                      <span className="inline-block mt-3 px-3 py-1 bg-teal-100 text-teal-700 text-xs font-semibold rounded-full">
                        {doc.file_category || 'General Document'}
                      </span>
                    </div>
                  </div>

                  {/* Footer */}
                  <div className="flex items-center justify-between mt-8 pt-4 border-t border-gray-100">
                    <span className="text-sm text-gray-500 italic">Free Download</span>

                    <button
                      onClick={() =>
                        handleDownloadClick({
                          ...doc,
                          title: doc.file_name,
                          file: doc.document_file,
                        })
                      }
                      className="flex items-center gap-2 px-5 py-2 rounded-xl font-semibold text-sm
                                bg-linear-to-r from-teal-600 to-blue-500 text-white
                                shadow-md hover:shadow-xl hover:scale-105
                                transition-all duration-300"
                    >
                      <Download size={16} />
                      Download
                    </button>
                  </div>
                </div>
              </ModernCardComponent>
            ))}
          </div>
        ) : (
          <ModernCardComponent className="p-12 text-center">
            <FileSearch size={64} className="text-gray-300 mx-auto mb-6" />
            <h3 className="text-2xl font-semibold text-gray-700 mb-3">No documents found</h3>
            <p className="text-gray-600 max-w-md mx-auto mb-6">
              {searchTerm ? `No results found for "${searchTerm}". Try adjusting your search terms.` : 'No documents available in this category at the moment.'}
            </p>
            <button 
              onClick={() => { setSearchTerm(''); setActiveCategory('all'); }}
              className="px-6 py-3 bg-linear-to-r from-teal-600 to-blue-500 text-white rounded-xl font-semibold hover:shadow-lg transition-all duration-300 transform hover:-translate-y-1"
            >
              View All Documents
            </button>
          </ModernCardComponent>
        )}
      </div>

      {/* Features Section */}
      <div className="py-16">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-12">
            <h2 className="text-3xl font-bold text-gray-900 mb-4">
              Why Choose Our Resources
            </h2>
            <p className="text-gray-600 max-w-2xl mx-auto">
              Premium academic materials curated for student success
            </p>
          </div>
          
          <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-6">
            <FeatureCardComponent
              Icon={Shield}
              title="Verified Content"
              description="All documents are officially verified and regularly updated"
              color="teal"
            />

            <FeatureCardComponent
              Icon={BookOpen}
              title="Comprehensive Library"
              description="Access a wide range of academic resources and forms"
              color="blue"
            />

            <FeatureCardComponent
              Icon={GraduationCap}
              title="Student-Focused"
              description="Resources specifically curated for modern students"
              color="emerald"
            />

            <FeatureCardComponent
              Icon={Zap}
              title="Instant Access"
              description="Download immediately after form submission"
              color="amber"
            />

            <FeatureCardComponent
              Icon={CheckCircle}
              title="Free Resources"
              description="All documents available at no cost to students"
              color="teal"
            />

            <FeatureCardComponent
              Icon={Sparkles}
              title="Regular Updates"
              description="New resources added weekly to keep you current"
              color="blue"
            />
          </div>
        </div>
      </div>

      {/* CTA Section */}
      <div className="pb-20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="bg-linear-to-r from-teal-600 to-blue-500 rounded-3xl p-12 text-center shadow-2xl">
            <h3 className="text-3xl md:text-4xl font-bold text-white mb-6">
              Need Additional Academic Support?
            </h3>
            <p className="text-white/90 text-lg md:text-xl mb-8 max-w-2xl mx-auto leading-relaxed">
              Can not find what you are looking for? Our dedicated student support team is ready to assist you 
              with any questions, document requests, or academic guidance you might need.
            </p>
            <div className="flex flex-col sm:flex-row gap-4 justify-center items-center">
              <Link href="/contact-us">
                <button className="px-8 py-4 bg-white cursor-pointer text-teal-700 font-semibold rounded-2xl hover:bg-gray-100 transition-all duration-300 transform hover:-translate-y-1 shadow-lg text-lg">
                  Contact Support Team
                </button>
              </Link>
              <Link href="/contact-us">
                <button className="px-8 py-4 bg-transparent border-2 cursor-pointer border-white text-white font-semibold rounded-2xl hover:bg-white hover:text-teal-700 transition-all duration-300 transform hover:-translate-y-1 text-lg">
                  Request Custom Document
                </button>
              </Link>
            </div>
          </div>
        </div>
      </div>

      {/* Enhanced Modal */}
      {selectedDoc && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm">
          <ModernCardComponent className="relative w-full max-w-md animate-scale-in">
            <button
              onClick={() => setSelectedDoc(null)}
              className="absolute top-6 right-6 text-gray-500 hover:text-gray-700 p-2 rounded-full hover:bg-gray-100 transition"
            >
              <X size={24} />
            </button>
            
            <div className="p-8">
              <div className="text-center mb-6">
                <div className="p-3 rounded-xl bg-linear-to-r from-teal-50 to-blue-50 border border-teal-100 mx-auto mb-4 w-20 h-20 flex items-center justify-center">
                  <Download size={32} className="text-teal-600" />
                </div>
                <h2 className="text-2xl font-bold text-gray-900 mb-2">
                  Download {selectedDoc.title}
                </h2>
                <p className="text-gray-600">Please provide your details to access this academic resource</p>
              </div>
              
              <form onSubmit={handleSubmit} className="space-y-6">
                <CustomInputComponent
                  Icon={User}
                  placeholder="Enter Your Full Name"
                  name="name"
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  required
                />

                <CustomInputComponent
                  Icon={Mail}
                  placeholder="your.email@university.edu"
                  type="email"
                  name="email"
                  value={formData.email}
                  onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                  required
                />

                <CustomInputComponent
                  Icon={Phone}
                  placeholder="Your contact number"
                  name="phone"
                  value={formData.phone}
                  onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                  required
                />

                <button
                  type="submit"
                  className="w-full group/btn cursor-pointer bg-linear-to-r from-teal-600 to-blue-500 text-white font-semibold py-4 rounded-xl hover:shadow-xl transition-all duration-300 flex items-center justify-center gap-3"
                >
                  <Download className="w-5 h-5" />
                  <span>Submit & Download Document</span>
                  <ArrowRight className="w-5 h-5 transition-transform duration-300 group-hover/btn:translate-x-1" />
                </button>
                
                <div className="flex items-center justify-center text-xs text-gray-500 mt-6">
                  <Shield className="w-4 h-4 text-teal-600 mr-2" />
                  <span>Your data is secure and protected</span>
                </div>
              </form>
            </div>
          </ModernCardComponent>
        </div>
      )}
    </div>
  );
}