// apps/verify/src/pages/Results.jsx
import React, { useState, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { 
  ArrowLeft, 
  CheckCircle, 
  TrendingUp, 
  Clock, 
  Users, 
  DollarSign,
  Target,
  Loader2,
  AlertCircle
} from 'lucide-react';
// FIX 1: Import image as standard default URL asset
import logoImg from '../assets/logo.png';
import api from '../../../../services/api/client';
import config from '../config';

// FIX 2: Create a lightweight local Logo component if needed
function Logo({ size = 'lg', withText = true }) {
  const sizeClasses = size === 'lg' ? 'h-10' : 'h-8';
  return (
    <div className="flex items-center gap-2">
      <img src={logoImg} alt="SkillNexus Logo" className={`${sizeClasses} w-auto object-contain`} />
      {withText && <span className="font-bold text-xl text-gray-900">SkillNexus</span>}
    </div>
  );
}

export function Results() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const auditId = searchParams.get('id');
  
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [result, setResult] = useState(null);
  const [auditData, setAuditData] = useState(null);

  useEffect(() => {
    if (!auditId) {
      setError('No audit ID provided');
      setLoading(false);
      return;
    }

    const fetchResults = async () => {
      try {
        setLoading(true);
        const response = await api.audit.get(auditId);
        if (response.success) {
          setAuditData(response.data);
          setResult({
            score: response.data.severity_score || 75,
            monthlyHires: response.data.monthly_hires || 10,
            avgTimeToHire: response.data.avg_time_to_hire || 30,
            recommendations: typeof response.data.recommendations === 'string' 
              ? JSON.parse(response.data.recommendations) 
              : response.data.recommendations || [],
            estimatedSavings: typeof response.data.estimated_savings === 'string' 
              ? JSON.parse(response.data.estimated_savings) 
              : response.data.estimated_savings || {}
          });
        } else {
          setError('Failed to load audit results');
        }
      } catch (err) {
        console.error('Error fetching audit results:', err);
        setError(err.message || 'Failed to load results');
      } finally {
        setLoading(false);
      }
    };

    fetchResults();
  }, [auditId]);

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-gray-50 via-white to-primary-50/20 flex items-center justify-center">
        <div className="text-center">
          <Loader2 className="w-12 h-12 text-primary-600 animate-spin mx-auto mb-4" />
          <p className="text-gray-600">Loading your audit results...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-gray-50 via-white to-primary-50/20 flex items-center justify-center p-4">
        <div className="bg-white rounded-2xl shadow-card border border-gray-100 p-8 max-w-md w-full text-center">
          <AlertCircle className="w-16 h-16 text-red-500 mx-auto mb-4" />
          <h2 className="text-2xl font-bold text-gray-900 mb-2">Something Went Wrong</h2>
          <p className="text-gray-600 mb-6">{error}</p>
          <button 
            onClick={() => navigate('/')}
            className="px-6 py-3 bg-primary-600 text-white rounded-xl hover:bg-primary-700 transition-colors"
          >
            Return Home
          </button>
        </div>
      </div>
    );
  }

  if (!result) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-gray-50 via-white to-primary-50/20 flex items-center justify-center p-4">
        <div className="bg-white rounded-2xl shadow-card border border-gray-100 p-8 max-w-md w-full text-center">
          <p className="text-gray-600">No results found</p>
          <button 
            onClick={() => navigate('/')}
            className="mt-4 px-6 py-3 bg-primary-600 text-white rounded-xl hover:bg-primary-700 transition-colors"
          >
            Go Home
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 via-white to-primary-50/20">
      <div className="container mx-auto px-4 py-8 max-w-3xl">
        <button 
          onClick={() => navigate('/')}
          className="inline-flex items-center gap-2 text-sm font-medium text-gray-600 hover:text-primary-600 transition-colors mb-8 group"
        >
          <ArrowLeft className="w-4 h-4 group-hover:-translate-x-1 transition-transform" />
          Back to Home
        </button>

        <div className="flex items-center gap-4 mb-8">
          <Logo size="lg" withText={true} />
        </div>

        <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-card border border-gray-100 p-8">
          <div className="text-center mb-8">
            <div className="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <CheckCircle className="w-10 h-10 text-green-600" />
            </div>
            <h1 className="text-3xl font-bold text-gray-900">Audit Complete!</h1>
            <p className="text-gray-600 mt-2">
              {auditData?.company_name ? `Results for ${auditData.company_name}` : 'Your hiring audit results are ready'}
            </p>
            {auditData?.created_at && (
              <p className="text-xs text-gray-400 mt-1">
                Generated: {new Date(auditData.created_at).toLocaleString()}
              </p>
            )}
          </div>

          <div className="grid grid-cols-3 gap-4 mb-8">
            <div className="bg-primary-50 p-4 rounded-lg text-center border border-primary-100">
              <div className="text-2xl font-bold text-primary-600">{result.score}%</div>
              <div className="text-sm text-gray-600">Hiring Score</div>
            </div>
            <div className="bg-green-50 p-4 rounded-lg text-center border border-green-100">
              <div className="text-2xl font-bold text-green-600">{result.monthlyHires}</div>
              <div className="text-sm text-gray-600">Monthly Hires</div>
            </div>
            <div className="bg-amber-50 p-4 rounded-lg text-center border border-amber-100">
              <div className="text-2xl font-bold text-amber-600">{result.avgTimeToHire}</div>
              <div className="text-sm text-gray-600">Days to Hire</div>
            </div>
          </div>

          {/* Estimated Savings */}
          {result.estimatedSavings && (
            <div className="bg-gradient-to-r from-emerald-50 to-teal-50 p-6 rounded-xl border border-emerald-200 mb-6">
              <h3 className="font-semibold text-gray-900 mb-3 flex items-center gap-2">
                <DollarSign className="w-5 h-5 text-emerald-600" />
                Estimated Annual Savings
              </h3>
              <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                <div>
                  <div className="text-sm text-gray-600">Current Cost</div>
                  <div className="text-lg font-bold text-gray-900">
                    ${(result.estimatedSavings.currentAnnualCost || 0).toLocaleString()}
                  </div>
                </div>
                <div>
                  <div className="text-sm text-gray-600">With SkillNexus</div>
                  <div className="text-lg font-bold text-green-600">
                    ${(result.estimatedSavings.projectedAnnualCost || 0).toLocaleString()}
                  </div>
                </div>
                <div>
                  <div className="text-sm text-gray-600">Total Savings</div>
                  <div className="text-lg font-bold text-emerald-600">
                    ${(result.estimatedSavings.annualSavings || 0).toLocaleString()}
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Recommendations */}
          {result.recommendations && result.recommendations.length > 0 && (
            <div className="space-y-4 mb-6">
              <h3 className="font-semibold text-gray-900 flex items-center gap-2">
                <Target className="w-5 h-5 text-primary-600" />
                Recommendations
              </h3>
              {result.recommendations.map((rec, index) => (
                <div key={index} className="bg-primary-50 p-4 rounded-lg border border-primary-100">
                  <p className="font-medium text-gray-900">{rec.title || rec}</p>
                  {rec.description && (
                    <p className="text-sm text-gray-600">{rec.description}</p>
                  )}
                  {rec.timeframe && (
                    <span className="text-xs text-primary-600 mt-1 inline-block">
                      ⏱️ {rec.timeframe}
                    </span>
                  )}
                </div>
              ))}
            </div>
          )}

          <div className="flex flex-col sm:flex-row gap-4">
            <button 
              onClick={() => navigate('/register')}
              className="flex-1 px-6 py-3 bg-gradient-to-r from-primary-600 to-secondary-600 text-white rounded-xl font-medium hover:shadow-primary transition-all duration-300"
            >
              Get Started with SkillNexus
            </button>
            <button 
              onClick={() => navigate('/')}
              className="flex-1 px-6 py-3 border border-gray-300 text-gray-700 rounded-xl font-medium hover:bg-gray-50 transition-colors"
            >
              Back to Home
            </button>
          </div>

          {/* Environment indicator */}
          <div className="mt-6 text-center">
            <span className="text-xs text-gray-400">
              {config.isProduction ? '🚀 Production' : config.isStaging ? '🧪 Staging' : '💻 Development'} • 
              API: {config.apiUrl}
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}