'use client';

import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import axios from 'axios';

const Home = () => {
  const router = useRouter();

  const [userId, setUserId] = useState<string | null>(null);
  const [user, setUser] = useState<string | null>(null);
  const [userDetails, setUserDetails] = useState<any>({});

  const fetchUsers = async () => {
    try {
      const uid = localStorage.getItem("data4auto_uid");
      const res: any = await axios.get(`https://ebay.backend.data4autos.com/api/motorstate/auth/users/${uid}`);
      setUserDetails(res.data?.user || []);
    } catch (err) {
      console.error(err);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  // Authentication check
  useEffect(() => {
    const uid = localStorage.getItem('data4auto_uid');
    const userEmail = localStorage.getItem('d4a_email');

    if (uid && userEmail) {
      setUserId(uid);
      setUser(userEmail);
    } else {
      axios
        .get('https://ebay.backend.data4autos.com/api/auth/protected', {
          withCredentials: true,
        })
        .then((res: any) => {
          if (res?.data?.payment !== null) {
            setUser(res.data.user?.email);
            setUserId(res.data.user.userid);
            localStorage.setItem('d4a_auth_uid', res.data.user.userid);
          } else {
            router.push('/pricing');
          }
        })
        .catch(() => {
          router.push('/login');
        });
    }
  }, [router]);

  if (!userId && !user) {
    return (
      <div className="flex h-screen items-center justify-center text-gray-600 text-lg">
        🔐 Checking authentication...
      </div>
    );
  }

  const cards = [
    {
      id: 1,
      title: '🎥 How to Access Your Store',
      content: (
        <div className="relative w-full h-56 rounded-2xl overflow-hidden shadow-lg">
          <iframe
            className="absolute top-0 left-0 w-full h-full rounded-2xl"
            src="https://www.youtube.com/embed/g6qV2cQ2Fhw?si=CYpzlvUEahw0eUn7"
            allowFullScreen
          />
        </div>
      ),
    },
    {
      id: 2,
      title: '📊 About Data4Autos',
      content: (
        <p className="text-gray-700 leading-relaxed">
          Data4Autos is an advanced automation platform for eCommerce sellers.
          Connect, manage, and automate your Motor State and eBay stores effortlessly — all in one place.
        </p>
      ),
    },
    {
      id: 3,
      title: '⚙️ About Motor StateStateStateStateState Integration',
      content: (
        <p className="text-gray-700 leading-relaxed">
          Sync your Motor StateState account to autgfhjklomatically import products, pricing, and stock updates.
        </p>
      ),
    },
    {
      id: 4,
      title: '🛒 About eBay Integration',
      content: (
        <p className="text-gray-700 leading-relaxed">
          Manage your eBay listing automation, stock updates, and orders from one dashboard.
        </p>
      ),
    },
    {
      id: 5,
      title: '💰 Pricing & Plans',
      content: (
        <div className="flex flex-col items-center gap-2">
          <p className="text-gray-700 text-center leading-relaxed">
            Explore flexible pricing options designed for every business size.
          </p>
          <button
            onClick={() => router.push('/pricing')}
            className="mt-3 bg-[#0099cc] text-white px-6 py-2 rounded-full font-medium shadow-md hover:scale-105 transition"
          >
            View Pricing
          </button>
        </div>
      ),
    },
    {
      id: 6,
      title: '👤 User Details',
      content: (
        <div className="text-gray-700 space-y-2 text-center">
          <p><strong>Name:</strong> {userDetails?.name}</p>
          <p><strong>Email:</strong> {userDetails?.email}</p>
          <p><strong>Phone:</strong> {userDetails?.phonenumber}</p>
        </div>
      ),
    },
  ];

  const cardColors = [
    "bg-gradient-to-br from-[#ffecd2] to-[#fcb69f]",
    "bg-gradient-to-br from-[#a1c4fd] to-[#c2e9fb]",
    "bg-gradient-to-br from-[#fbc2eb] to-[#a6c1ee]",
    "bg-gradient-to-br from-[#d4fc79] to-[#96e6a1]",
    "bg-gradient-to-br from-[#84fab0] to-[#8fd3f4]",
    "bg-gradient-to-br from-[#fccb90] to-[#d57eeb]"
  ];

  return (
    <div className="min-h-screen bg-[#eef9ff] px-6 py-14">

      {/* ⭐ HERO SECTION WITH IMAGE BACKGROUND ⭐ */}
      <div className="w-full mx-auto mb-16">
        <div className="relative overflow-hidden rounded-3xl shadow-xl h-[320px] md:h-[380px] lg:h-[420px]">

          {/* Background Image */}
          <img
            src="https://data4autos.com/assets/img/contact/contact-banner-bg.webp"
            className="absolute inset-0 w-full h-full object-cover"
          />

          {/* Dark Overlay */}
          <div className="absolute inset-0 bg-black/40"></div>

          {/* Gradient Overlay */}
          <div className="absolute inset-0 bg-gradient-to-r from-[#00d1ff99]/60 via-[#ffffff00] to-[#212529ab]"></div>

          {/* Glow Blurs */}
          <div className="absolute -top-10 -left-10 w-40 h-40 bg-white/20 blur-3xl rounded-full"></div>
          <div className="absolute bottom-0 right-0 w-60 h-60 bg-blue-300/20 blur-3xl rounded-full"></div>

          {/* Center Text */}
          <div className="relative z-10 flex flex-col items-center justify-center h-full text-center px-6">
            <h1 className="text-5xl font-extrabold text-white drop-shadow-lg">
              Welcome Back, {userDetails?.name || "User"} 👋
            </h1>

            <p className="text-white/90 mt-4 text-lg max-w-2xl">
              Manage your eBay & Motor State store with powerful automation tools.
            </p>
          </div>
        </div>
      </div>

      {/* DASHBOARD CARDS */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-12 mx-auto">
        {cards.map((card, index) => (
          <div
            key={card.id}
            className={`relative overflow-hidden rounded-3xl p-8 shadow-lg hover:shadow-2xl hover:-translate-y-3 transition duration-500 ${cardColors[index]}`}
          >
            <h2 className="text-2xl font-extrabold mb-4 text-center">
              {card.title}
            </h2>
            <div>{card.content}</div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default Home;
