import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import html2canvas from "html2canvas";
import { MobileBottomNav } from "@/components/assessment/MobileBottomNav";
import { AssessmentHeader } from "@/components/assessment/AssessmentHeader";
import { AssessmentDialogs } from "@/components/assessment/AssessmentDialogs";
import { AssessmentSteps } from "@/components/assessment/AssessmentSteps";
import { Footer } from "@/components/layout/Footer";
import { StampSection } from "@/components/layout/StampSection";
import { BenchmarkConsentModal } from "@/components/result/BenchmarkConsentModal";
import { useAssessmentPersistence } from "@/hooks/useAssessmentPersistence";
import { useAssessmentLogic } from "@/hooks/useAssessmentLogic";
import { useAssessmentHandlers } from "@/hooks/useAssessmentHandlers";
import { useToast } from "@/hooks/use-toast";
import { useSEO } from "@/hooks/useSEO";
import { HowToSchema } from "@/components/seo/StructuredData";
import { 
  mapCompanyAge, 
  mapTeamSize, 
  mapFundingTotal, 
  mapFundingRound, 
  mapFinalCategory,
  countActions 
} from "@/utils/assessmentDataMapper";
import { CORE_ACTIONS_BY_LEVEL, BONUS_ACTIONS_BY_LEVEL, CORE_KEYS, BONUS_KEYS } from "@/lib/maturity/config";

// Self-Assessment page with 3 steps (visual refresh)
export default function Assessment() {
  // Enhanced SEO for Assessment page
  useSEO({
    title: "Sustainability Assessment Tool - daphni | ESG Maturity Evaluation",
    description: "Take our comprehensive sustainability assessment in 3 steps. Answer 4 questions, select your implemented actions, and get your personalized ESG maturity score with actionable recommendations.",
    keywords: [
      "sustainability assessment",
      "ESG evaluation",
      "maturity scoring",
      "sustainability actions",
      "environmental assessment",
      "social responsibility check",
      "governance evaluation",
      "startup ESG tool",
      "daphni assessment",
      "sustainability calculator"
    ],
    canonicalUrl: "/assessment",
    ogType: "website",
    ogImage: "https://lovable.dev/opengraph-image-p98pqg.png",
    twitterCard: "summary_large_image",
    lang: "en"
  });

  // Step 1 – Maturity inputs and validation
  const { 
    answers, 
    core, 
    bonus, 
    isMaturityValidated, 
    isActionsValidated,
    hasStoredData,
    lastSaved,
    updateAnswers,
    updateCore,
    updateBonus,
    setIsMaturityValidated,
    setIsActionsValidated,
    resetMaturity,
    resetAssessment
  } = useAssessmentPersistence();

  // Assessment logic
  const {
    allAnswered,
    level,
    band,
    levelLabel,
    breakdown,
    coreCategories,
    availableBonuses,
    remainingCore,
    remainingBonus,
    category,
    marketingCat,
    scorePct
  } = useAssessmentLogic(answers, core, bonus, updateCore, updateBonus);
  
  const [showMaturityDialog, setShowMaturityDialog] = useState(false);
  const [showCategoryDialog, setShowCategoryDialog] = useState(false);
  const [showConsentModal, setShowConsentModal] = useState(false);
  const [currentStep, setCurrentStep] = useState<1 | 2 | 3>(1);
  const { toast } = useToast();
  const navigate = useNavigate();

  const handlers = useAssessmentHandlers({
    updateAnswers,
    updateCore,
    updateBonus,
    setIsMaturityValidated,
    setIsActionsValidated,
    setShowMaturityDialog,
    setShowCategoryDialog,
    setCurrentStep,
    resetAssessment,
    resetMaturity,
    allAnswered: !!allAnswered
  });

  // Auto-advance steps based on validation state
  useEffect(() => {
    if (isActionsValidated) {
      setCurrentStep(3);
    } else if (isMaturityValidated) {
      setCurrentStep(2);
    } else {
      setCurrentStep(1);
    }
  }, [isMaturityValidated, isActionsValidated]);

  // Notify user when data is restored
  useEffect(() => {
    if (hasStoredData) {
      toast({
        title: "Assessment restored",
        description: "Your previous answers have been automatically restored.",
        duration: 3000,
      });
    }
  }, []);

  // Navigation handlers with optimized scrolling
  const handleStepClick = (step: 1 | 2 | 3) => {
    const scrollToElement = (id: string) => {
      requestAnimationFrame(() => {
        const element = document.getElementById(id);
        if (element) {
          element.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
      });
    };

    if (step === 1) {
      scrollToElement('maturity');
    } else if (step === 2) {
      if (isMaturityValidated) {
        scrollToElement('actions');
      } else {
        scrollToElement('maturity');
      }
    } else if (step === 3) {
      if (isActionsValidated) {
        scrollToElement('result-title');
      } else if (isMaturityValidated) {
        scrollToElement('actions');
      } else {
        scrollToElement('maturity');
      }
    }
    setCurrentStep(step);
  };

  // Handle benchmark flow
  const handleGetBenchmark = () => {
    console.log('🎯 Opening benchmark consent modal...');
    console.log('Assessment data:', prepareAssessmentData());
    setShowConsentModal(true);
  };

  const handleBenchmarkSuccess = (token: string) => {
    setShowConsentModal(false);
    navigate(`/result/${token}`);
  };

  const handleBenchmarkSkip = () => {
    setShowConsentModal(false);
    // Scroll back to results section
    requestAnimationFrame(() => {
      const resultElement = document.getElementById('result-title');
      if (resultElement) {
        resultElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    });
  };

  // Prepare assessment data for database
  const prepareAssessmentData = () => {
    if (!level || !answers.inception || !answers.employees || !answers.totalFunding || !answers.fundingRound) {
      return null;
    }

    const coreCount = countActions(core);
    const bonusCount = countActions(bonus);
    
    // Calculate total available actions based on level
    const coreTotal = CORE_KEYS.filter(k => CORE_ACTIONS_BY_LEVEL[level][k]).length;
    const bonusTotal = BONUS_KEYS.filter(k => BONUS_ACTIONS_BY_LEVEL[level][k]).length;

    return {
      maturity_level: `Level ${level}`,
      company_age: mapCompanyAge(answers.inception),
      team_size: mapTeamSize(answers.employees),
      funding_total: mapFundingTotal(answers.totalFunding),
      funding_round: mapFundingRound(answers.fundingRound),
      score_global: Math.round(scorePct),
      core_completed: coreCount,
      core_total_available: coreTotal,
      bonus_completed: bonusCount,
      bonus_total_available: bonusTotal,
      final_category: mapFinalCategory(category.id),
    };
  };

  // Copy score card as PNG with optimized rendering
  const handleCopyScoreCard = async () => {
    const scoreCardElement = document.querySelector('[data-score-card]') as HTMLElement;
    if (!scoreCardElement) return;
    
    try {
      // Use requestAnimationFrame to ensure DOM is stable before capturing
      await new Promise(resolve => requestAnimationFrame(resolve));
      
      const canvas = await html2canvas(scoreCardElement, {
        backgroundColor: '#ffffff',
        scale: 2,
        useCORS: true,
        allowTaint: true,
        windowWidth: scoreCardElement.scrollWidth,
        windowHeight: scoreCardElement.scrollHeight,
      });
      
      canvas.toBlob(async (blob) => {
        if (!blob) return;
        
        try {
          await navigator.clipboard.write([
            new ClipboardItem({
              'image/png': blob
            })
          ]);
          toast({
            title: "Score card copied!",
            description: "The score card has been copied to your clipboard as an image.",
            duration: 3000,
          });
        } catch (err) {
          // Fallback: download image
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = 'sustainability-score-card.png';
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          URL.revokeObjectURL(url);
          
          toast({
            title: "Score card downloaded!",
            description: "The score card has been downloaded as an image.",
            duration: 3000,
          });
        }
      }, 'image/png');
    } catch (error) {
      toast({
        title: "Error",
        description: "Failed to copy score card. Please try again.",
        variant: "destructive",
        duration: 3000,
      });
    }
  };
  
  return (
    <>
      {/* Structured Data for Assessment Page */}
      <HowToSchema />
      
      <main id="main-content" className="min-h-screen bg-background pb-20 md:pb-0" role="main">
        <AssessmentHeader
          isCompleted={isMaturityValidated && isActionsValidated}
          hasStoredData={hasStoredData}
          lastSaved={lastSaved}
          onRestart={handlers.handleRestart}
        />

        {/* Main Content - Full Width */}
        <div className="container max-w-6xl mx-auto px-6 pt-12 pb-1">
          <AssessmentSteps
            answers={answers}
            updateAnswers={updateAnswers}
            isMaturityValidated={isMaturityValidated}
            allAnswered={!!allAnswered}
            level={level}
            levelLabel={levelLabel}
            band={band as 'early' | 'growth' | 'expansion' | 'established'}
            breakdown={breakdown}
            isActionsValidated={isActionsValidated}
            coreCategories={coreCategories}
            availableBonuses={availableBonuses}
            core={core}
            bonus={bonus}
            updateCore={updateCore}
            updateBonus={updateBonus}
            marketingCat={marketingCat}
            scorePct={scorePct}
            remainingCore={remainingCore}
            remainingBonus={remainingBonus}
            handlers={handlers}
            onCopyScoreCard={handleCopyScoreCard}
            onGetBenchmark={isActionsValidated ? handleGetBenchmark : undefined}
          />
        </div>

        {/* Mobile Navigation - Only visible on mobile */}
        <MobileBottomNav
          currentStep={currentStep}
          isMaturityValidated={isMaturityValidated}
          isActionsValidated={isActionsValidated}
          onStepClick={handleStepClick}
        />

        {/* Dialogs */}
        <AssessmentDialogs
          showMaturityDialog={showMaturityDialog}
          showCategoryDialog={showCategoryDialog}
          onMaturityDialogChange={setShowMaturityDialog}
          onCategoryDialogChange={setShowCategoryDialog}
        />

        {/* Benchmark Consent Modal */}
        {prepareAssessmentData() && (
          <>
            {console.log('✅ Rendering BenchmarkConsentModal. Open:', showConsentModal)}
            <BenchmarkConsentModal
              open={showConsentModal}
              onOpenChange={setShowConsentModal}
              assessmentData={prepareAssessmentData()!}
              onSuccess={handleBenchmarkSuccess}
              onSkip={handleBenchmarkSkip}
            />
          </>
        )}

        <StampSection />
        <Footer />
      </main>
    </>
  );
}