import React, { useState } from 'react';
import { Award, CheckCircle, AlertCircle, Search, Shield, FileCheck, Calendar, User, BookOpen, GraduationCap } from 'lucide-react';
import { supabase, type Certificate } from '../lib/supabase';

const CertificateVerificationPage = () => {
  const [certificateId, setCertificateId] = useState('');
  const [verificationResult, setVerificationResult] = useState<{
    status: 'valid' | 'invalid';
    details?: Certificate;
    message?: string;
  } | null>(null);
  const [loading, setLoading] = useState(false);

  const handleCertificateVerification = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!certificateId.trim()) return;

    setLoading(true);
    setVerificationResult(null);
    
    try {
      const { data, error } = await supabase
        .from('certificates')
        .select('*')
        .eq('certificate_id', certificateId.trim())
        .eq('is_valid', true)
        .single();

      if (error || !data) {
        setVerificationResult({
          status: 'invalid',
          message: 'Certificate not found or invalid. Please check the ID and try again.'
        });
      } else {
        setVerificationResult({
          status: 'valid',
          details: data
        });
      }
    } catch (error) {
      console.error('Error verifying certificate:', error);
      setVerificationResult({
        status: 'invalid',
        message: 'An error occurred during verification. Please try again.'
      });
    } finally {
      setLoading(false);
    }
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-purple-50 pt-20">
      {/* Hero Section */}
      <section className="py-20">
        <div className="container mx-auto px-4 text-center">
          <div className="max-w-4xl mx-auto">
            <div className="bg-white rounded-full w-24 h-24 flex items-center justify-center mx-auto mb-8 shadow-lg">
              <Shield className="h-12 w-12 text-blue-600" />
            </div>
            <h1 className="text-5xl font-bold text-gray-900 mb-6">Certificate Verification</h1>
            <p className="text-xl text-gray-600 mb-8">
              Verify the authenticity of Zouis Corp certifications instantly. 
              Enter your certificate ID below to confirm your credentials.
            </p>
          </div>
        </div>
      </section>

      {/* Verification Form */}
      <section className="pb-20">
        <div className="container mx-auto px-4">
          <div className="max-w-2xl mx-auto">
            <div className="bg-white rounded-2xl shadow-xl p-8 md:p-12">
              <div className="text-center mb-8">
                <Award className="h-16 w-16 text-blue-600 mx-auto mb-4" />
                <h2 className="text-2xl font-bold text-gray-900 mb-2">Verify Your Certificate</h2>
                <p className="text-gray-600">
                  Enter your certificate ID to verify the authenticity of your Zouis Corp certification.
                </p>
              </div>

              <form onSubmit={handleCertificateVerification} className="space-y-6">
                <div>
                  <label htmlFor="certificateId" className="block text-sm font-medium text-gray-700 mb-2">
                    Certificate ID *
                  </label>
                  <div className="relative">
                    <Search className="h-5 w-5 absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" />
                    <input
                      type="text"
                      id="certificateId"
                      value={certificateId}
                      onChange={(e) => setCertificateId(e.target.value)}
                      placeholder="Enter your certificate ID (e.g., ZC-2024-001234)"
                      className="w-full pl-10 pr-4 py-4 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-lg"
                      required
                    />
                  </div>
                  <p className="text-sm text-gray-500 mt-2">
                    Your certificate ID can be found on your certificate document
                  </p>
                </div>

                <button
                  type="submit"
                  disabled={loading || !certificateId.trim()}
                  className="w-full bg-gradient-to-r from-blue-600 to-purple-600 text-white py-4 px-6 rounded-lg font-semibold hover:shadow-lg transform hover:scale-105 transition-all duration-300 flex items-center justify-center space-x-2 disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none"
                >
                  {loading ? (
                    <>
                      <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                      <span>Verifying...</span>
                    </>
                  ) : (
                    <>
                      <span>Verify Certificate</span>
                      <FileCheck className="h-5 w-5" />
                    </>
                  )}
                </button>
              </form>

              {/* Verification Result */}
              {verificationResult && (
                <div className="mt-8">
                  {verificationResult.status === 'valid' && verificationResult.details ? (
                    <div className="border-2 border-green-200 bg-green-50 rounded-xl p-6">
                      <div className="flex items-center mb-6">
                        <CheckCircle className="h-8 w-8 text-green-600 mr-3" />
                        <div>
                          <h3 className="text-xl font-bold text-green-800">Certificate Verified ✓</h3>
                          <p className="text-green-700">This certificate is authentic and valid</p>
                        </div>
                      </div>
                      
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div className="space-y-4">
                          <div className="flex items-start space-x-3">
                            <User className="h-5 w-5 text-green-600 mt-1" />
                            <div>
                              <p className="font-semibold text-green-800">Student Name</p>
                              <p className="text-green-700">{verificationResult.details.student_name}</p>
                            </div>
                          </div>
                          
                          <div className="flex items-start space-x-3">
                            <BookOpen className="h-5 w-5 text-green-600 mt-1" />
                            <div>
                              <p className="font-semibold text-green-800">Course</p>
                              <p className="text-green-700">{verificationResult.details.course_name}</p>
                            </div>
                          </div>
                          
                          <div className="flex items-start space-x-3">
                            <GraduationCap className="h-5 w-5 text-green-600 mt-1" />
                            <div>
                              <p className="font-semibold text-green-800">Instructor</p>
                              <p className="text-green-700">{verificationResult.details.instructor}</p>
                            </div>
                          </div>
                        </div>
                        
                        <div className="space-y-4">
                          <div className="flex items-start space-x-3">
                            <Award className="h-5 w-5 text-green-600 mt-1" />
                            <div>
                              <p className="font-semibold text-green-800">Certificate ID</p>
                              <p className="text-green-700 font-mono">{verificationResult.details.certificate_id}</p>
                            </div>
                          </div>
                          
                          <div className="flex items-start space-x-3">
                            <Calendar className="h-5 w-5 text-green-600 mt-1" />
                            <div>
                              <p className="font-semibold text-green-800">Issue Date</p>
                              <p className="text-green-700">{formatDate(verificationResult.details.issue_date)}</p>
                            </div>
                          </div>
                          
                          <div className="flex items-start space-x-3">
                            <CheckCircle className="h-5 w-5 text-green-600 mt-1" />
                            <div>
                              <p className="font-semibold text-green-800">Grade</p>
                              <p className="text-green-700">{verificationResult.details.grade}</p>
                            </div>
                          </div>
                        </div>
                      </div>
                      
                      <div className="mt-6 p-4 bg-green-100 rounded-lg">
                        <p className="text-sm text-green-800">
                          <strong>Verification completed on:</strong> {new Date().toLocaleDateString('en-US', {
                            year: 'numeric',
                            month: 'long',
                            day: 'numeric',
                            hour: '2-digit',
                            minute: '2-digit'
                          })}
                        </p>
                      </div>
                    </div>
                  ) : (
                    <div className="border-2 border-red-200 bg-red-50 rounded-xl p-6">
                      <div className="flex items-center mb-4">
                        <AlertCircle className="h-8 w-8 text-red-600 mr-3" />
                        <div>
                          <h3 className="text-xl font-bold text-red-800">Verification Failed</h3>
                          <p className="text-red-700">Certificate could not be verified</p>
                        </div>
                      </div>
                      <p className="text-red-700 mb-4">{verificationResult.message}</p>
                      <div className="bg-red-100 p-4 rounded-lg">
                        <p className="text-sm text-red-800">
                          <strong>Common issues:</strong>
                        </p>
                        <ul className="text-sm text-red-700 mt-2 space-y-1">
                          <li>• Certificate ID may be entered incorrectly</li>
                          <li>• Certificate may have been revoked or expired</li>
                          <li>• Certificate may not be issued by Zouis Corp</li>
                        </ul>
                      </div>
                    </div>
                  )}
                </div>
              )}

              {/* Help Section */}
              <div className="mt-8 p-6 bg-blue-50 rounded-xl">
                <h4 className="font-bold text-blue-900 mb-3 flex items-center">
                  <Award className="h-5 w-5 mr-2" />
                  Need Help?
                </h4>
                <p className="text-blue-800 mb-4">
                  If you're having trouble verifying your certificate or have questions about the verification process, 
                  our support team is here to help.
                </p>
                <div className="space-y-2 text-sm text-blue-700">
                  <p><strong>Email:</strong> certificates@zouiscorp.com</p>
                  <p><strong>Phone:</strong> +1 (555) 123-4567</p>
                  <p><strong>Hours:</strong> Monday - Friday, 9:00 AM - 6:00 PM EST</p>
                </div>
              </div>

              {/* Sample Certificate ID */}
              <div className="mt-6 p-4 bg-gray-50 rounded-lg">
                <p className="text-sm text-gray-600">
                  <strong>Sample Certificate ID for testing:</strong> ZC-2024-001234
                </p>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Features Section */}
      <section className="py-16 bg-white">
        <div className="container mx-auto px-4">
          <div className="text-center mb-12">
            <h2 className="text-3xl font-bold text-gray-900 mb-4">Why Verify Certificates?</h2>
            <p className="text-xl text-gray-600 max-w-3xl mx-auto">
              Certificate verification ensures authenticity and builds trust in professional credentials.
            </p>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-3 gap-8 max-w-4xl mx-auto">
            <div className="text-center">
              <div className="bg-blue-100 w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4">
                <Shield className="h-8 w-8 text-blue-600" />
              </div>
              <h3 className="font-bold text-gray-900 mb-2">Instant Verification</h3>
              <p className="text-gray-600 text-sm">Get immediate confirmation of certificate authenticity</p>
            </div>
            
            <div className="text-center">
              <div className="bg-green-100 w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4">
                <CheckCircle className="h-8 w-8 text-green-600" />
              </div>
              <h3 className="font-bold text-gray-900 mb-2">Secure & Reliable</h3>
              <p className="text-gray-600 text-sm">Our verification system is secure and tamper-proof</p>
            </div>
            
            <div className="text-center">
              <div className="bg-purple-100 w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4">
                <Award className="h-8 w-8 text-purple-600" />
              </div>
              <h3 className="font-bold text-gray-900 mb-2">Detailed Information</h3>
              <p className="text-gray-600 text-sm">Access complete certificate details and metadata</p>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
};

export default CertificateVerificationPage;