'use client';

import * as React from 'react';
import { useState, useMemo, useEffect, useRef } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { motion, AnimatePresence } from 'framer-motion';
import { ChevronRight, ChevronLeft, Send, Check } from 'lucide-react';
import * as QRCode from 'qrcode';

import { FormState, Step } from './ContactForm/types';
import { PRICING, initialState } from './ContactForm/constants';
import { PriceCalculation } from './ContactForm/components/PriceCalculation';
import { ShareModal } from './ShareModal';

// Steps
import { TypeStep } from './ContactForm/steps/TypeStep';
import { CompanyStep } from './ContactForm/steps/CompanyStep';
import { PresenceStep } from './ContactForm/steps/PresenceStep';
import { BaseStep } from './ContactForm/steps/BaseStep';
import { FeaturesStep } from './ContactForm/steps/FeaturesStep';
import { DesignStep } from './ContactForm/steps/DesignStep';
import { AssetsStep } from './ContactForm/steps/AssetsStep';
import { FunctionsStep } from './ContactForm/steps/FunctionsStep';
import { ApiStep } from './ContactForm/steps/ApiStep';
import { ContentStep } from './ContactForm/steps/ContentStep';
import { LanguageStep } from './ContactForm/steps/LanguageStep';
import { TimelineStep } from './ContactForm/steps/TimelineStep';
import { ContactStep } from './ContactForm/steps/ContactStep';
import { WebAppStep } from './ContactForm/steps/WebAppStep';

import { 
  ConceptTarget, 
  ConceptWebsite, 
  ConceptPrototyping, 
  ConceptCommunication, 
  ConceptSystem, 
  ConceptCode, 
  ConceptAutomation, 
  ConceptPrice, 
  HeroArchitecture 
} from './Landing/ConceptIllustrations';

export function ContactForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [stepIndex, setStepIndex] = useState(0);
  const [state, setState] = useState<FormState>(initialState);
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [isClient, setIsClient] = useState(false);
  const [qrCodeData, setQrCodeData] = useState<string>('');
  const [isShareModalOpen, setIsShareModalOpen] = useState(false);
  const [hoveredStep, setHoveredStep] = useState<number | null>(null);
  const formContainerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    setIsClient(true);
  }, []);

  // URL Binding
  useEffect(() => {
    const step = searchParams.get('step');
    if (step) setStepIndex(parseInt(step));

    const config = searchParams.get('config');
    if (config) {
      try {
        const decoded = JSON.parse(decodeURIComponent(escape(atob(config))));
        setState(s => ({ ...s, ...decoded }));
      } catch (e) {
        console.error("Failed to decode config", e);
      }
    }
  }, []);

  const currentUrl = useMemo(() => {
    if (!isClient) return '';
    const params = new URLSearchParams();
    params.set('step', stepIndex.toString());
    
    const configData = {
      projectType: state.projectType,
      companyName: state.companyName,
      employeeCount: state.employeeCount,
      existingWebsite: state.existingWebsite,
      socialMedia: state.socialMedia,
      socialMediaUrls: state.socialMediaUrls,
      existingDomain: state.existingDomain,
      wishedDomain: state.wishedDomain,
      websiteTopic: state.websiteTopic,
      selectedPages: state.selectedPages,
      otherPages: state.otherPages,
      otherPagesCount: state.otherPagesCount,
      features: state.features,
      otherFeatures: state.otherFeatures,
      otherFeaturesCount: state.otherFeaturesCount,
      functions: state.functions,
      otherFunctions: state.otherFunctions,
      otherFunctionsCount: state.otherFunctionsCount,
      apiSystems: state.apiSystems,
      otherTech: state.otherTech,
      otherTechCount: state.otherTechCount,
      assets: state.assets,
      otherAssets: state.otherAssets,
      otherAssetsCount: state.otherAssetsCount,
      cmsSetup: state.cmsSetup,
      languagesList: state.languagesList,
      deadline: state.deadline,
      designVibe: state.designVibe,
      colorScheme: state.colorScheme,
      targetAudience: state.targetAudience,
      userRoles: state.userRoles,
      dataSensitivity: state.dataSensitivity,
      platformType: state.platformType,
      dontKnows: state.dontKnows,
      visualStaging: state.visualStaging,
      complexInteractions: state.complexInteractions
    };
    
    const stateString = btoa(unescape(encodeURIComponent(JSON.stringify(configData))));
    params.set('config', stateString);
    
    return `${window.location.origin}${window.location.pathname}?${params.toString()}`;
  }, [state, stepIndex, isClient]);

  useEffect(() => {
    if (currentUrl) {
      router.replace(currentUrl, { scroll: false });
      QRCode.toDataURL(currentUrl, { margin: 1, width: 200 }).then(setQrCodeData);
    }
  }, [currentUrl]);

  const totalPagesCount = useMemo(() => {
    return state.selectedPages.length + state.otherPages.length + (state.otherPagesCount || 0);
  }, [state.selectedPages, state.otherPages, state.otherPagesCount]);

  const totalPrice = useMemo(() => {
    if (state.projectType !== 'website') return 0;

    let total = PRICING.BASE_WEBSITE;
    total += totalPagesCount * PRICING.PAGE;
    total += (state.features.length + state.otherFeatures.length + (state.otherFeaturesCount || 0)) * PRICING.FEATURE;
    total += (state.functions.length + state.otherFunctions.length + (state.otherFunctionsCount || 0)) * PRICING.FUNCTION;
    total += (state.apiSystems.length + state.otherTech.length + (state.otherTechCount || 0)) * PRICING.API_INTEGRATION;
    total += (state.newDatasets || 0) * PRICING.NEW_DATASET;

    if (state.cmsSetup) {
      total += PRICING.CMS_SETUP;
      total += (state.features.length + state.otherFeatures.length + (state.otherFeaturesCount || 0)) * PRICING.CMS_CONNECTION_PER_FEATURE;
    }

    // Multi-language factor (e.g. +20% per additional language)
    const languagesCount = state.languagesList.length || 1;
    if (languagesCount > 1) {
      total *= (1 + (languagesCount - 1) * 0.2);
    }

    return Math.round(total);
  }, [state, totalPagesCount]);

  const monthlyPrice = useMemo(() => {
    if (state.projectType !== 'website') return 0;
    return PRICING.HOSTING_MONTHLY + (state.storageExpansion * PRICING.STORAGE_EXPANSION_MONTHLY);
  }, [state]);

  const updateState = (updates: Partial<FormState>) => {
    setState((s) => ({ ...s, ...updates }));
  };

  const toggleItem = (list: string[], id: string) => {
    return list.includes(id) ? list.filter(i => i !== id) : [...list, id];
  };

  const scrollToTop = () => {
    if (formContainerRef.current) {
      const offset = 120;
      const bodyRect = document.body.getBoundingClientRect().top;
      const elementRect = formContainerRef.current.getBoundingClientRect().top;
      const elementPosition = elementRect - bodyRect;
      const offsetPosition = elementPosition - offset;

      window.scrollTo({
        top: offsetPosition,
        behavior: 'smooth'
      });
    }
  };

  const nextStep = () => {
    if (stepIndex < activeSteps.length - 1) {
      setStepIndex(stepIndex + 1);
      setTimeout(scrollToTop, 50);
    }
  };

  const prevStep = () => {
    if (stepIndex > 0) {
      setStepIndex(stepIndex - 1);
      setTimeout(scrollToTop, 50);
    }
  };

  const steps: Step[] = [
    { id: 'type', title: 'Das Ziel', description: 'Was möchten Sie realisieren?', illustration: <ConceptTarget className="w-full h-full" /> },
    { id: 'company', title: 'Unternehmen', description: 'Wer sind Sie?', illustration: <ConceptCommunication className="w-full h-full" /> },
    { id: 'presence', title: 'Präsenz', description: 'Bestehende Kanäle.', illustration: <ConceptSystem className="w-full h-full" /> },
    { id: 'features', title: 'Die Systeme', description: 'Welche inhaltlichen Bereiche planen wir?', illustration: <ConceptPrototyping className="w-full h-full" /> },
    { id: 'base', title: 'Die Seiten', description: 'Welche Seiten benötigen wir?', illustration: <ConceptWebsite className="w-full h-full" /> },
    { id: 'design', title: 'Design-Wünsche', description: 'Wie soll die Seite wirken?', illustration: <ConceptCommunication className="w-full h-full" /> },
    { id: 'assets', title: 'Ihre Assets', description: 'Was bringen Sie bereits mit?', illustration: <ConceptSystem className="w-full h-full" /> },
    { id: 'functions', title: 'Die Logik', description: 'Welche Funktionen werden benötigt?', illustration: <ConceptCode className="w-full h-full" /> },
    { id: 'api', title: 'Schnittstellen', description: 'Datenaustausch mit Drittsystemen.', illustration: <ConceptAutomation className="w-full h-full" /> },
    { id: 'content', title: 'Die Pflege', description: 'Wer kümmert sich um die Daten?', illustration: <ConceptPrice className="w-full h-full" /> },
    { id: 'language', title: 'Sprachen', description: 'Globale Reichweite planen.', illustration: <ConceptCommunication className="w-full h-full" /> },
    { id: 'timeline', title: 'Zeitplan', description: 'Wann soll das Projekt live gehen?', illustration: <HeroArchitecture className="w-full h-full" /> },
    { id: 'contact', title: 'Abschluss', description: 'Erzählen Sie mir mehr über Ihr Vorhaben.', illustration: <ConceptCommunication className="w-full h-full" /> },
    { id: 'webapp', title: 'Web App Details', description: 'Spezifische Anforderungen für Ihre Anwendung.', illustration: <ConceptSystem className="w-full h-full" /> },
  ];

  const activeSteps = useMemo(() => {
    if (state.projectType === 'website') {
      return steps.filter(s => s.id !== 'webapp');
    }
    // Web App flow
    return [
      steps.find(s => s.id === 'type')!,
      steps.find(s => s.id === 'company')!,
      steps.find(s => s.id === 'presence')!,
      steps.find(s => s.id === 'webapp')!,
      { ...steps.find(s => s.id === 'functions')!, title: 'Funktionen', description: 'Kern-Features Ihrer Anwendung.' },
      { ...steps.find(s => s.id === 'api')!, title: 'Integrationen', description: 'Anbindung an bestehende Systeme.' },
      steps.find(s => s.id === 'timeline')!,
      steps.find(s => s.id === 'contact')!,
    ];
  }, [state.projectType]);

  useEffect(() => {
    if (stepIndex >= activeSteps.length) setStepIndex(activeSteps.length - 1);
  }, [activeSteps, stepIndex]);

  const renderStepContent = () => {
    const currentStep = activeSteps[stepIndex];
    switch (currentStep.id) {
      case 'type':
        return <TypeStep state={state} updateState={updateState} />;
      case 'company':
        return <CompanyStep state={state} updateState={updateState} />;
      case 'presence':
        return <PresenceStep state={state} updateState={updateState} toggleItem={toggleItem} />;
      case 'base':
        return <BaseStep state={state} updateState={updateState} toggleItem={toggleItem} />;
      case 'features':
        return <FeaturesStep state={state} updateState={updateState} toggleItem={toggleItem} />;
      case 'design':
        return <DesignStep state={state} updateState={updateState} />;
      case 'assets':
        return <AssetsStep state={state} updateState={updateState} toggleItem={toggleItem} />;
      case 'functions':
        return <FunctionsStep state={state} updateState={updateState} toggleItem={toggleItem} />;
      case 'api':
        return <ApiStep state={state} updateState={updateState} toggleItem={toggleItem} />;
      case 'content':
        return <ContentStep state={state} updateState={updateState} />;
      case 'language':
        return <LanguageStep state={state} updateState={updateState} />;
      case 'timeline':
        return <TimelineStep state={state} updateState={updateState} />;
      case 'contact':
        return <ContactStep state={state} updateState={updateState} />;
      case 'webapp':
        return <WebAppStep state={state} updateState={updateState} />;
      default: return null;
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (stepIndex === activeSteps.length - 1) {
      // Handle submission
      const mailBody = `
        Name: ${state.name}
        Email: ${state.email}
        Rolle: ${state.role}
        Projekt: ${state.projectType}
        Konfiguration: ${currentUrl}
        
        Nachricht:
        ${state.message}
      `;
      window.location.href = `mailto:marc@mintel.me?subject=Projektanfrage: ${state.name}&body=${encodeURIComponent(mailBody)}`;
      setIsSubmitted(true);
    } else {
      nextStep();
    }
  };

  const handleShare = () => {
    setIsShareModalOpen(true);
  };

  if (isSubmitted) {
    return (
      <motion.div initial={{ opacity: 0, scale: 0.95 }} animate={{ opacity: 1, scale: 1 }} className="p-12 md:p-24 bg-slate-900 text-white rounded-[4rem] text-center space-y-12">
        <div className="w-24 h-24 bg-white text-slate-900 rounded-full flex items-center justify-center mx-auto"><Check size={48} strokeWidth={3} /></div>
        <div className="space-y-6"><h2 className="text-5xl font-bold tracking-tight">Anfrage gesendet!</h2><p className="text-slate-400 text-2xl max-w-2xl mx-auto leading-relaxed">Vielen Dank, {state.name.split(' ')[0]}. Ich melde mich innerhalb von 24 Stunden bei Ihnen.</p></div>
        <button type="button" onClick={() => { setIsSubmitted(false); setStepIndex(0); setState(initialState); }} className="text-slate-400 hover:text-white transition-colors underline underline-offset-8 text-lg focus:outline-none overflow-hidden relative rounded-full">Neue Anfrage starten</button>
      </motion.div>
    );
  }

  return (
    <div ref={formContainerRef} className="grid grid-cols-1 lg:grid-cols-12 gap-16 items-start">
      <div className="lg:col-span-8 space-y-12">
        <div className="flex flex-col gap-10">
          <div className="flex flex-col md:flex-row md:items-center gap-8">
            <div className="w-32 h-32 shrink-0 bg-slate-50 rounded-[2.5rem] p-4 flex items-center justify-center">{activeSteps[stepIndex].illustration}</div>
            <div className="space-y-2">
              <span className="text-base font-bold uppercase tracking-[0.2em] text-slate-400">Schritt {stepIndex + 1} von {activeSteps.length}</span>
              <h3 className="text-4xl font-bold tracking-tight text-slate-900">{activeSteps[stepIndex].title}</h3>
              <p className="text-xl text-slate-500 leading-relaxed">{activeSteps[stepIndex].description}</p>
            </div>
          </div>
          <div className="flex gap-3 h-4">
            {activeSteps.map((step, i) => (
              <div 
                key={i} 
                className="flex-1 h-full flex items-center relative"
                onMouseEnter={() => setHoveredStep(i)}
                onMouseLeave={() => setHoveredStep(null)}
              >
                <button
                  type="button"
                  onClick={() => {
                    setStepIndex(i);
                    setTimeout(scrollToTop, 50);
                  }}
                  className={`w-full h-full rounded-full transition-all duration-700 ${i <= stepIndex ? 'bg-slate-900' : 'bg-slate-100'} cursor-pointer focus:outline-none p-0 border-none`}
                />
                <AnimatePresence>
                  {hoveredStep === i && (
                    <motion.div 
                      initial={{ opacity: 0, y: 5, x: '-50%' }}
                      animate={{ opacity: 1, y: 0, x: '-50%' }}
                      exit={{ opacity: 0, y: 5, x: '-50%' }}
                      className="absolute bottom-full left-1/2 mb-3 px-4 py-2 bg-slate-900 text-white text-sm font-bold uppercase tracking-wider rounded-lg whitespace-nowrap pointer-events-none z-50 shadow-xl"
                    >
                      {step.title}
                      <div className="absolute top-full left-1/2 -translate-x-1/2 -mt-1 border-4 border-transparent border-t-slate-900" />
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>
            ))}
          </div>
        </div>

        <div className="flex justify-between items-center py-6 border-y border-slate-50">
          {stepIndex > 0 ? (
            <button type="button" onClick={prevStep} className="text-base font-bold uppercase tracking-widest text-slate-400 hover:text-slate-900 transition-colors flex items-center gap-2 focus:outline-none relative overflow-hidden rounded-full">
              <ChevronLeft size={18} /> Zurück
            </button>
          ) : <div />}
          <div className="flex items-center gap-4">
            {stepIndex < activeSteps.length - 1 && (
              <button type="button" onClick={nextStep} className="text-base font-bold uppercase tracking-widest text-slate-400 hover:text-slate-900 transition-colors flex items-center gap-2 focus:outline-none relative overflow-hidden rounded-full">
                Weiter <ChevronRight size={18} />
              </button>
            )}
          </div>
        </div>

        <form onSubmit={handleSubmit} className="min-h-[450px]">
          <AnimatePresence mode="wait"><motion.div key={activeSteps[stepIndex].id} initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -20 }} transition={{ duration: 0.4, ease: [0.23, 1, 0.32, 1] }}>{renderStepContent()}</motion.div></AnimatePresence>
          <div className="flex justify-between mt-16">
            {stepIndex > 0 ? (<button type="button" onClick={prevStep} className="flex items-center gap-3 px-10 py-5 rounded-full border border-slate-200 hover:border-slate-900 transition-all font-bold text-xl focus:outline-none overflow-hidden relative rounded-full"><ChevronLeft size={24} /> Zurück</button>) : <div />}
            {stepIndex < activeSteps.length - 1 ? (<button type="button" onClick={nextStep} className="flex items-center gap-3 px-10 py-5 rounded-full bg-slate-900 text-white hover:bg-slate-800 transition-all font-bold text-xl shadow-xl shadow-slate-200 focus:outline-none overflow-hidden relative rounded-full">Weiter <ChevronRight size={24} /></button>) : (<button type="submit" disabled={!state.email || !state.name} className="flex items-center gap-3 px-10 py-5 rounded-full bg-slate-900 text-white hover:bg-slate-800 transition-all font-bold text-xl disabled:opacity-50 disabled:cursor-not-allowed shadow-xl shadow-slate-200 focus:outline-none overflow-hidden relative rounded-full">Anfrage senden <Send size={24} /></button>)}
          </div>
        </form>
      </div>
      <PriceCalculation 
        state={state} 
        totalPrice={totalPrice} 
        monthlyPrice={monthlyPrice} 
        totalPagesCount={totalPagesCount} 
        isClient={isClient} 
        qrCodeData={qrCodeData} 
        onShare={handleShare}
      />

      <ShareModal 
        isOpen={isShareModalOpen} 
        onClose={() => setIsShareModalOpen(false)} 
        url={currentUrl} 
        qrCodeData={qrCodeData} 
      />
    </div>
  );
}
