"use client";
import React, { useState } from "react";
import { motion, AnimatePresence } from "motion/react";
import { BackgroundRippleEffect } from "@/components/layout/BackgroundRippleEffect";
import Shuffle from "@/components/ui/Shuffle";
import ColourfulText from "@/components/ui/colourful-text";
import { PlaceholdersAndVanishInput } from "@/components/ui/placeholders-and-vanish-input";
import { MultiStepLoader } from "@/components/ui/multi-step-loader";
import { IPhoneNotification } from "@/components/ui/iphone-notification";
import { parseEbayAccount } from "@/services/ebayParserService";
import { createManagedAccount, fetchManagedAccounts } from "@/services/accountsService";
import { account, databases, databaseId, usersCollectionId } from "@/lib/appwrite";

export const OnboardingGate = ({ userName, onStart, loading, error }) => {
  const [phase, setPhase] = useState("shuffle");
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");
  const [showNotification, setShowNotification] = useState(false);
  const [notificationMessage, setNotificationMessage] = useState("bitte eine gueltige url verwenden!");
  const [skipHovered, setSkipHovered] = useState(false);

  const loadingStates = [
    { text: "URL wird verarbeitet..." },
    { text: "Account-Daten werden geladen..." },
    { text: "Account wird erstellt..." },
    { text: "Fast fertig..." },
  ];

  const placeholders = [
    "Gib deine eBay-Account-URL ein...",
    "z.B. https://www.ebay.de/str/username",
    "Paste deine eBay Shop-URL hier...",
  ];

  const handleOverlayClick = async (e) => {
    // Only handle clicks on the overlay itself or when in shuffle phase
    if (phase === "shuffle") {
      // Create user document first (but don't call onStart, as that would hide the gate)
      // We need to create it directly to ensure it exists for account creation later
      try {
        const authUser = await account.get();
        if (authUser && databases && databaseId && usersCollectionId) {
          try {
            await databases.createDocument(
              databaseId,
              usersCollectionId,
              authUser.$id,
              {
                user_name: authUser.name || "User"
              }
            );
          } catch (docErr) {
            // 409 Conflict means document already exists - that's ok
            if (docErr.code !== 409 && docErr.type !== 'document_already_exists') {
              console.warn("Fehler beim Erstellen des User-Dokuments:", docErr);
            }
          }
        }
      } catch (err) {
        console.error("Fehler beim Abrufen des Users oder Erstellen des Dokuments:", err);
        // Continue anyway - might already exist
      }
      
      // Add small delay to let the shuffle exit animation complete
      // Exit animation is 0.5s, so we wait a bit longer to see it fully
      setTimeout(() => {
        setPhase("input");
      }, 600); // 600ms delay - slightly longer than exit animation (500ms)
    }
  };

  const handleSkip = async () => {
    // Skip onboarding - directly call onStart to proceed to dashboard
    // Must await to ensure User document is created before proceeding
    if (onStart) {
      await onStart();
    }
  };

  // Validate eBay URL
  const isValidEbayUrl = (url) => {
    // #region agent log
    fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:45',message:'isValidEbayUrl: entry',data:{url,hasUrl:!!url,trimmedUrl:url?.trim()},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'A'})}).catch(()=>{});
    // #endregion
    
    if (!url || !url.trim()) {
      // #region agent log
      fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:48',message:'isValidEbayUrl: empty url',data:{},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'A'})}).catch(()=>{});
      // #endregion
      return false;
    }
    
    // Pattern for hostname only (without protocol/path)
    const ebayHostnamePattern = /^(www\.)?(ebay\.(de|com|co\.uk|fr|it|es|nl|at|ch|com\.au|ca)|ebay-kleinanzeigen\.de)$/i;
    
    try {
      const urlObj = new URL(url);
      const hostname = urlObj.hostname;
      const patternMatches = ebayHostnamePattern.test(hostname);
      
      // #region agent log
      fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:62',message:'isValidEbayUrl: validation result',data:{url,hostname,patternMatches,pattern:ebayHostnamePattern.toString()},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'A'})}).catch(()=>{});
      // #endregion
      
      return patternMatches;
    } catch (e) {
      // Invalid URL format
      // #region agent log
      fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:62',message:'isValidEbayUrl: URL parse error',data:{url,error:e.message},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'A'})}).catch(()=>{});
      // #endregion
      return false;
    }
  };

  const handleAccountSubmit = async (e, url) => {
    e.preventDefault();
    
    // #region agent log
    fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:59',message:'handleAccountSubmit: entry',data:{url,hasUrl:!!url,phase},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'B'})}).catch(()=>{});
    // #endregion
    
    if (!url || !url.trim()) {
      // #region agent log
      fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:64',message:'handleAccountSubmit: empty url, showing notification',data:{},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'B'})}).catch(()=>{});
      // #endregion
      setNotificationMessage("bitte eine gueltige url verwenden!");
      setShowNotification(true);
      return;
    }

    // Validate eBay URL
    const isValid = isValidEbayUrl(url);
    // #region agent log
    fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:71',message:'handleAccountSubmit: validation result',data:{url,isValid},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'A'})}).catch(()=>{});
    // #endregion
    
    if (!isValid) {
      // #region agent log
      fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:76',message:'handleAccountSubmit: invalid url, showing notification',data:{url},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'A'})}).catch(()=>{});
      // #endregion
      setNotificationMessage("bitte eine gueltige url verwenden!");
      setShowNotification(true);
      return;
    }

    setSubmitting(true);
    setSubmitError("");

    // Wait 2 seconds for vanish animation, then switch to loading phase
    setTimeout(async () => {
      // Switch to loading phase first
      setPhase("loading");

      try {
        // #region agent log
        fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:88',message:'handleAccountSubmit: before parseEbayAccount',data:{url},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'C'})}).catch(()=>{});
        // #endregion
        
        // Parse eBay account
        const accountData = await parseEbayAccount(url);
        
        // #region agent log
        fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:93',message:'handleAccountSubmit: parseEbayAccount success',data:{url,hasAccountData:!!accountData,market:accountData?.market,sellerId:accountData?.sellerId},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'C'})}).catch(()=>{});
        // #endregion

        // Validate that sellerId was extracted successfully
        if (!accountData.sellerId || accountData.sellerId.trim() === "") {
          throw new Error("Die eBay-URL konnte nicht verarbeitet werden. Bitte stelle sicher, dass es eine gültige eBay-Shop-URL ist.");
        }

        // Get current user
        const authUser = await account.get();

        // Check for duplicate account before creating
        const existingAccounts = await fetchManagedAccounts(authUser.$id);
        const duplicateAccount = existingAccounts.find(
          (acc) =>
            acc.account_platform_account_id === accountData.sellerId &&
            acc.account_platform_market === accountData.market
        );

        if (duplicateAccount) {
          throw new Error("Dieser Account ist bereits verbunden.");
        }

        // Create account in database
        await createManagedAccount(authUser.$id, {
          account_platform_market: accountData.market,
          account_platform_account_id: accountData.sellerId,
          account_shop_name: accountData.shopName || null,
          account_url: url,
          account_status: accountData.status || "active",
        });

        // Account erstellt erfolgreich, rufe onStart auf
        onStart && onStart();
        
        // Trigger event to reload Dashboard accounts
        // #region agent log
        fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:142',message:'handleAccountSubmit: account created, triggering reload event',data:{url},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'B'})}).catch(()=>{});
        // #endregion
        window.dispatchEvent(new CustomEvent('accountsUpdated'));
      } catch (err) {
        console.error("Fehler beim Erstellen des Accounts:", err);
        
        // #region agent log
        fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:106',message:'handleAccountSubmit: error caught',data:{url,errorMessage:err.message,errorCode:err.code,errorType:err.type,errorStack:err.stack?.substring(0,200)},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'C'})}).catch(()=>{});
        // #endregion
        
        // Show notification for URL validation, duplicate, or parsing errors
        if (
          err.message?.includes("URL") || 
          err.message?.includes("ungültig") || 
          err.message?.includes("invalid") ||
          err.message?.includes("bereits verbunden") ||
          err.message?.includes("already")
        ) {
          // #region agent log
          fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:205',message:'handleAccountSubmit: URL/duplicate error, showing notification',data:{errorMessage:err.message},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'C'})}).catch(()=>{});
          // #endregion
          // Use the actual error message or default message
          setNotificationMessage(err.message || "bitte eine gueltige url verwenden!");
          setShowNotification(true);
        } else {
          // #region agent log
          fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:175',message:'handleAccountSubmit: non-URL error, setting submitError',data:{errorMessage:err.message},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'C'})}).catch(()=>{});
          // #endregion
          setSubmitError(err.message || "Fehler beim Erstellen des Accounts. Bitte versuche es erneut.");
        }
        setPhase("input");
        setSubmitting(false);
      }
    }, 2000); // 2 second delay for vanish animation
  };

  return (
    <div 
      style={{...styles.overlay, cursor: phase === "shuffle" ? "pointer" : "default"}} 
      onClick={handleOverlayClick}
    >
      <BackgroundRippleEffect />
      
      {/* Skip Button - Bottom Left */}
      <button
        onClick={handleSkip}
        style={{
          ...styles.skipButton,
          width: skipHovered ? "90px" : "32px",
          borderRadius: skipHovered ? "40px" : "50%",
        }}
        onMouseEnter={() => setSkipHovered(true)}
        onMouseLeave={() => setSkipHovered(false)}
      >
        <div style={{
          ...styles.skipSign,
          width: skipHovered ? "30%" : "100%",
          paddingLeft: skipHovered ? "15px" : "0",
        }}>
          <svg viewBox="0 0 512 512" style={{ width: "12px" }}>
            <path fill="white" d="M470.6 278.6c12.5-12.5 12.5-32.8 0-45.3l-160-160c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L402.7 256 265.4 393.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0l160-160zm-352 160l160-160c12.5-12.5 12.5-32.8 0-45.3l-160-160c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L210.7 256 73.4 393.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0z" />
          </svg>
        </div>
        <div style={{
          ...styles.skipText,
          opacity: skipHovered ? 1 : 0,
          width: skipHovered ? "70%" : "0%",
          paddingRight: skipHovered ? "8px" : "0",
        }}>Skip</div>
      </button>
      
      {/* iPhone-style Notification */}
      <IPhoneNotification
        show={showNotification}
        title="Einstellungen"
        message={notificationMessage}
        onClose={() => setShowNotification(false)}
        duration={4000}
      />
      
      {/* Shuffle and Input Phases - Combined AnimatePresence for smooth transition */}
      <AnimatePresence mode="wait">
        {phase === "shuffle" && (
          <motion.div
            key="shuffle"
            initial={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 100 }}
            transition={{ duration: 0.5, ease: "easeInOut" }}
            style={styles.centerContent}
            onClick={(e) => {
              e.stopPropagation(); // Prevent double-triggering
              handleOverlayClick(e);
            }}
          >
            <div style={styles.shuffleContainer}>
              <Shuffle
                text="Willkommen"
                duration={1}
                stagger={0.08}
                shuffleDirection="down"
                loop={true}
                loopDelay={2}
                triggerOnHover={false}
                style={{ letterSpacing: '0.2em' }}
              />
              <span style={styles.staticComma}>,</span>
              <Shuffle
                text={userName}
                duration={1}
                stagger={0.08}
                shuffleDirection="down"
                loop={true}
                loopDelay={2}
                triggerOnHover={false}
                style={{ letterSpacing: '0.2em', marginLeft: '0.3em' }}
              />
            </div>
          </motion.div>
        )}
        
        {phase === "input" && (
          <motion.div
            key="input"
            initial={{ opacity: 0, y: -100 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -100 }}
            transition={{ duration: 0.5, ease: "easeInOut" }}
            style={styles.centerContent}
          >
            <div style={styles.inputContainer}>
              <div style={styles.colourfulTextContainer}>
                <span style={styles.textPrefix}>Gib deine </span>
                <ColourfulText text="ebay account url" />
                <span style={styles.textPrefix}> ein</span>
              </div>
              
              <PlaceholdersAndVanishInput
                placeholders={placeholders}
                onChange={() => {
                  setSubmitError("");
                  setShowNotification(false);
                  setNotificationMessage("bitte eine gueltige url verwenden!"); // Reset to default
                }}
                onSubmit={handleAccountSubmit}
              />

              {(submitError || error) && !showNotification && (
                <div style={styles.error}>
                  {submitError || error}
                </div>
              )}
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Loading Phase */}
      {phase === "loading" && (
        <MultiStepLoader
          loadingStates={loadingStates}
          loading={true}
          duration={2000}
          loop={false}
        />
      )}
    </div>
  );
};

const styles = {
  overlay: {
    position: "fixed",
    inset: 0,
    background: "rgba(0,0,0,0.75)",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    padding: 18,
    zIndex: 9998,
    overflow: "hidden",
  },
  centerContent: {
    position: "relative",
    zIndex: 10, // Higher than BackgroundRippleEffect (z-[3] = z-index: 3) to ensure input is clickable
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "center",
    width: "100%",
    maxWidth: "800px",
    padding: "0 20px",
    cursor: "default",
  },
  shuffleContainer: {
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    flexWrap: "wrap",
    gap: "0",
  },
  staticComma: {
    fontSize: "4rem",
    fontWeight: 800,
    color: "#e7aaf0",
    marginLeft: "0.1em",
    marginRight: "0.1em",
    display: "inline-block",
  },
  inputContainer: {
    width: "100%",
    maxWidth: "600px",
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    gap: "24px",
  },
  colourfulTextContainer: {
    display: "flex",
    alignItems: "center",
    flexWrap: "wrap",
    justifyContent: "center",
    gap: "4px",
    fontSize: "24px",
    fontWeight: 600,
    color: "#e7aaf0",
    marginBottom: "8px",
    textAlign: "center",
  },
  textPrefix: {
    color: "#e7aaf0",
  },
  error: {
    marginTop: 12,
    color: "#ffb3b3",
    fontSize: 13,
    textAlign: "center",
    padding: "8px 16px",
    backgroundColor: "rgba(255, 179, 179, 0.1)",
    borderRadius: "8px",
    border: "1px solid rgba(255, 179, 179, 0.3)",
  },
  skipButton: {
    position: "fixed",
    bottom: 20,
    left: 20,
    display: "flex",
    alignItems: "center",
    justifyContent: "flex-start",
    width: "32px",
    height: "32px",
    border: "none",
    borderRadius: "50%",
    cursor: "pointer",
    backgroundColor: "rgb(255, 65, 65)",
    boxShadow: "2px 2px 10px rgba(0, 0, 0, 0.199)",
    transition: "all 0.3s ease",
    overflow: "hidden",
    zIndex: 10001,
  },
  skipSign: {
    width: "100%",
    transition: "all 0.3s ease",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
  },
  skipText: {
    position: "absolute",
    right: "0%",
    width: "0%",
    opacity: 0,
    color: "white",
    fontSize: "0.9em",
    fontWeight: 600,
    transition: "all 0.3s ease",
    whiteSpace: "nowrap",
  },
};
