import React, { useMemo, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  Search,
  Bell,
  Menu,
  Home,
  Flame,
  PlaySquare,
  Clock3,
  ThumbsUp,
  Download,
  History,
  Settings,
  LogIn,
  Upload,
  SlidersHorizontal,
  ChevronLeft,
  ChevronRight,
} from "lucide-react";

// Single-file OurTube UI — drop-in React component
// Styling: TailwindCSS (assumes Tailwind is available)
// Icons: lucide-react, Animations: framer-motion

// Dummy content — swap with your API later
const SAMPLE_VIDEOS = [
  {
    id: "1",
    title: "Building a Modern UI in 15 Minutes (No BS)",
    channel: "PixelSmith",
    views: 1280000,
    uploaded: "2 days ago",
    duration: "12:47",
    thumb:
      "https://images.unsplash.com/photo-1526498460520-4c246339dccb?q=80&w=1600&auto=format&fit=crop",
    src: "https://www.w3schools.com/html/mov_bbb.mp4",
    category: "Design",
  },
  {
    id: "2",
    title: "The GitHub Actions Crash Course I Wish I Had",
    channel: "DevDojo",
    views: 453221,
    uploaded: "1 week ago",
    duration: "9:03",
    thumb:
      "https://images.unsplash.com/photo-1542831371-d531d36971e6?q=80&w=1600&auto=format&fit=crop",
    src: "https://www.w3schools.com/html/movie.mp4",
    category: "Code",
  },
  {
    id: "3",
    title: "10 Chrome Flags That Actually Improve Your Life",
    channel: "BrowserLab",
    views: 21234,
    uploaded: "4 hours ago",
    duration: "7:55",
    thumb:
      "https://images.unsplash.com/photo-1498050108023-c5249f4df085?q=80&w=1600&auto=format&fit=crop",
    src: "https://www.w3schools.com/html/mov_bbb.mp4",
    category: "Tech",
  },
  {
    id: "4",
    title: "Make Liquid Glass Blur in Pure CSS (No Electron)",
    channel: "UI Alchemy",
    views: 987654,
    uploaded: "3 weeks ago",
    duration: "16:22",
    thumb:
      "https://images.unsplash.com/photo-1547658719-98cf1f2d2f98?q=80&w=1600&auto=format&fit=crop",
    src: "https://www.w3schools.com/html/movie.mp4",
    category: "Design",
  },
  {
    id: "5",
    title: "I Built a Mini OS in the Browser (OurTube Edition)",
    channel: "KernelKid",
    views: 752100,
    uploaded: "5 days ago",
    duration: "14:11",
    thumb:
      "https://images.unsplash.com/photo-1518779578993-ec3579fee39f?q=80&w=1600&auto=format&fit=crop",
    src: "https://www.w3schools.com/html/mov_bbb.mp4",
    category: "Code",
  },
  {
    id: "6",
    title: "Productivity Setup Tour 2025 — Clean, Minimal, Real",
    channel: "DeskTherapy",
    views: 154320,
    uploaded: "2 weeks ago",
    duration: "18:40",
    thumb:
      "https://images.unsplash.com/photo-1505740420928-5e560c06d30e?q=80&w=1600&auto=format&fit=crop",
    src: "https://www.w3schools.com/html/movie.mp4",
    category: "Lifestyle",
  },
  {
    id: "7",
    title: "The Fastest Way to Learn TypeScript in 2025",
    channel: "CodeCafe",
    views: 534210,
    uploaded: "3 days ago",
    duration: "22:01",
    thumb:
      "https://images.unsplash.com/photo-1555066931-4365d14bab8c?q=80&w=1600&auto=format&fit=crop",
    src: "https://www.w3schools.com/html/mov_bbb.mp4",
    category: "Code",
  },
  {
    id: "8",
    title: "AI Agents, But Actually Useful (No Hype)",
    channel: "Pragmatic AI",
    views: 84231,
    uploaded: "12 hours ago",
    duration: "11:28",
    thumb:
      "https://images.unsplash.com/photo-1518770660439-4636190af475?q=80&w=1600&auto=format&fit=crop",
    src: "https://www.w3schools.com/html/movie.mp4",
    category: "AI",
  },
];

const CATEGORIES = [
  "All",
  "Tech",
  "Code",
  "Design",
  "AI",
  "Lifestyle",
  "Gaming",
  "Music",
  "Podcasts",
  "News",
];

function formatViews(n) {
  if (n < 1000) return `${n}`;
  if (n < 1_000_000) return `${(n / 1000).toFixed(1)}K`;
  if (n < 1_000_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
  return `${(n / 1_000_000_000).toFixed(1)}B`;
}

function GlassCard({ children, className = "" }) {
  return (
    <div
      className={`rounded-2xl border border-white/10 bg-white/5 backdrop-blur-xl shadow-[0_2px_30px_rgba(0,0,0,0.2)] ${className}`}
    >
      {children}
    </div>
  );
}

function TopNav({ onToggleSidebar, query, setQuery, onSearch, sort, setSort }) {
  return (
    <div className="sticky top-0 z-40">
      <div className="flex items-center gap-3 px-4 sm:px-6 py-3 bg-gradient-to-b from-black/50 to-black/10 backdrop-blur-xl border-b border-white/10">
        <button
          onClick={onToggleSidebar}
          className="p-2 rounded-xl hover:bg-white/10 active:scale-95 transition"
          aria-label="Toggle sidebar"
        >
          <Menu className="w-5 h-5" />
        </button>

        <a href="#" className="flex items-center gap-2 font-semibold tracking-tight">
          <div className="w-7 h-7 rounded-xl bg-gradient-to-br from-pink-500 to-indigo-500 grid place-items-center text-white font-bold">O</div>
          <span className="text-xl">OurTube</span>
        </a>

        <div className="flex-1"></div>

        <div className="hidden md:flex items-center gap-2 max-w-xl w-full">
          <div className="flex-1">
            <GlassCard>
              <div className="flex items-center px-3">
                <Search className="w-4 h-4 opacity-70" />
                <input
                  value={query}
                  onChange={(e) => setQuery(e.target.value)}
                  onKeyDown={(e) => e.key === "Enter" && onSearch()}
                  placeholder="Search OurTube"
                  className="bg-transparent placeholder-white/50 outline-none px-2 py-2 w-full"
                />
                <button onClick={onSearch} className="px-2 py-2 hover:opacity-80">
                  <PlaySquare className="w-4 h-4" />
                </button>
              </div>
            </GlassCard>
          </div>

          <GlassCard>
            <button className="px-3 py-2 flex items-center gap-2">
              <Bell className="w-4 h-4" />
            </button>
          </GlassCard>
        </div>

        <div className="md:hidden">
          <button className="p-2 rounded-xl hover:bg-white/10">
            <Search className="w-5 h-5" />
          </button>
        </div>

        <GlassCard>
          <button className="px-3 py-2 flex items-center gap-2">
            <Upload className="w-4 h-4" />
            <span className="hidden sm:inline">Upload</span>
          </button>
        </GlassCard>

        <GlassCard>
          <button className="px-3 py-2 flex items-center gap-2">
            <LogIn className="w-4 h-4" />
            <span className="hidden sm:inline">Sign in</span>
          </button>
        </GlassCard>
      </div>

      <div className="px-4 sm:px-6 py-2 border-b border-white/10 bg-black/20 backdrop-blur-lg">
        <div className="flex items-center gap-2 overflow-x-auto no-scrollbar">
          <button className="p-2 rounded-lg hover:bg-white/10"><ChevronLeft className="w-4 h-4"/></button>
          {CATEGORIES.map((c) => (
            <button
              key={c}
              className={`px-3 py-1.5 rounded-full text-sm border border-white/10 hover:border-white/20 bg-white/5 hover:bg-white/10 transition`}
            >
              {c}
            </button>
          ))}
          <button className="p-2 rounded-lg hover:bg-white/10"><ChevronRight className="w-4 h-4"/></button>

          <div className="flex-1" />
          <GlassCard>
            <div className="flex items-center gap-2 px-3 py-1.5">
              <SlidersHorizontal className="w-4 h-4" />
              <select
                value={sort}
                onChange={(e) => setSort(e.target.value)}
                className="bg-transparent outline-none text-sm"
              >
                <option className="bg-black" value="relevant">Most relevant</option>
                <option className="bg-black" value="new">Newest</option>
                <option className="bg-black" value="views">Most viewed</option>
              </select>
            </div>
          </GlassCard>
        </div>
      </div>
    </div>
  );
}

function Sidebar({ open }) {
  return (
    <AnimatePresence>
      {open && (
        <motion.aside
          initial={{ x: -16, opacity: 0 }}
          animate={{ x: 0, opacity: 1 }}
          exit={{ x: -16, opacity: 0 }}
          transition={{ type: "spring", stiffness: 220, damping: 20 }}
          className="w-64 hidden lg:block h-[calc(100dvh-120px)] sticky top-[120px] p-3"
        >
          <nav className="space-y-2">
            <GlassCard>
              <ul className="p-2 text-sm">
                <SideLink icon={Home} label="Home" active />
                <SideLink icon={Flame} label="Trending" />
                <SideLink icon={History} label="History" />
                <SideLink icon={ThumbsUp} label="Liked" />
                <SideLink icon={Clock3} label="Watch later" />
                <SideLink icon={Download} label="Downloads" />
                <SideLink icon={Settings} label="Settings" />
              </ul>
            </GlassCard>
          </nav>
        </motion.aside>
      )}
    </AnimatePresence>
  );
}

function SideLink({ icon: Icon, label, active = false }) {
  return (
    <li>
      <a
        href="#"
        className={`flex items-center gap-3 rounded-xl px-3 py-2 hover:bg-white/10 transition ${
          active ? "bg-white/10" : ""
        }`}
      >
        <Icon className="w-4 h-4" />
        <span>{label}</span>
      </a>
    </li>
  );
}

function VideoGrid({ videos, onOpen }) {
  return (
    <div className="grid gap-4 sm:gap-6 grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
      {videos.map((v) => (
        <VideoCard key={v.id} v={v} onOpen={() => onOpen(v)} />
      ))}
    </div>
  );
}

function VideoCard({ v, onOpen }) {
  return (
    <motion.div whileHover={{ y: -3 }} className="cursor-pointer" onClick={onOpen}>
      <GlassCard className="overflow-hidden">
        <div className="relative">
          <img
            src={`${v.thumb}&sat=-50`}
            alt={v.title}
            className="w-full aspect-video object-cover"
            loading="lazy"
          />
          <span className="absolute bottom-2 right-2 text-xs bg-black/70 px-2 py-0.5 rounded-md">
            {v.duration}
          </span>
        </div>
        <div className="p-3">
          <div className="flex gap-3">
            <div className="w-10 h-10 rounded-full bg-white/10 shrink-0 grid place-items-center text-xs opacity-80">
              {v.channel[0]}
            </div>
            <div className="min-w-0">
              <h3 className="font-medium leading-snug line-clamp-2">{v.title}</h3>
              <p className="text-sm text-white/60 mt-0.5">{v.channel}</p>
              <p className="text-xs text-white/50 mt-1">
                {formatViews(v.views)} views • {v.uploaded}
              </p>
            </div>
          </div>
        </div>
      </GlassCard>
    </motion.div>
  );
}

function PlayerView({ video, onBack, onSelect }) {
  const related = useMemo(() => SAMPLE_VIDEOS.filter((v) => v.id !== video.id), [video]);
  return (
    <div className="grid grid-cols-1 xl:grid-cols-[1fr_360px] gap-6">
      <div>
        <GlassCard className="overflow-hidden">
          <div className="relative">
            <video src={video.src} controls className="w-full aspect-video bg-black"></video>
          </div>
          <div className="p-4">
            <div className="flex items-start gap-3">
              <button onClick={onBack} className="p-2 rounded-lg hover:bg-white/10"><ChevronLeft className="w-4 h-4"/></button>
              <div className="flex-1">
                <h1 className="text-xl font-semibold leading-tight">{video.title}</h1>
                <p className="text-sm text-white/60 mt-1">{video.channel} • {formatViews(video.views)} views • {video.uploaded}</p>
              </div>
              <div className="flex items-center gap-2">
                <GlassCard><button className="px-3 py-2 text-sm">Like</button></GlassCard>
                <GlassCard><button className="px-3 py-2 text-sm">Share</button></GlassCard>
                <GlassCard><button className="px-3 py-2 text-sm">Download</button></GlassCard>
              </div>
            </div>
          </div>
        </GlassCard>
        <GlassCard className="mt-4 p-4">
          <h2 className="font-semibold mb-2">Description</h2>
          <p className="text-sm text-white/80 leading-relaxed">
            This is a demo video inside OurTube — a clean, glassy YouTube-style UI. Replace the
            sample video URL with your own CDN or storage later.
          </p>
        </GlassCard>
      </div>

      <div className="space-y-3">
        {related.map((r) => (
          <button key={r.id} onClick={() => onSelect(r)} className="text-left w-full">
            <GlassCard className="overflow-hidden">
              <div className="grid grid-cols-[160px_1fr] gap-3">
                <div className="relative">
                  <img src={`${r.thumb}&sat=-50`} alt="thumb" className="w-full h-full object-cover aspect-video" />
                  <span className="absolute bottom-2 right-2 text-xs bg-black/70 px-2 py-0.5 rounded-md">
                    {r.duration}
                  </span>
                </div>
                <div className="py-2 pr-3">
                  <h3 className="font-medium leading-snug line-clamp-2">{r.title}</h3>
                  <p className="text-sm text-white/60 mt-0.5">{r.channel}</p>
                  <p className="text-xs text-white/50 mt-1">{formatViews(r.views)} views • {r.uploaded}</p>
                </div>
              </div>
            </GlassCard>
          </button>
        ))}
      </div>
    </div>
  );
}

export default function OurTubeApp() {
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [query, setQuery] = useState("");
  const [sort, setSort] = useState("relevant");
  const [selected, setSelected] = useState(null);

  const list = useMemo(() => {
    let arr = SAMPLE_VIDEOS.filter((v) =>
      [v.title, v.channel, v.category].join(" ").toLowerCase().includes(query.toLowerCase())
    );
    if (sort === "new") arr = [...arr].reverse();
    if (sort === "views") arr = [...arr].sort((a, b) => b.views - a.views);
    return arr;
  }, [query, sort]);

  return (
    <div className="min-h-[100dvh] text-white bg-[radial-gradient(1200px_600px_at_10%_-10%,rgba(59,130,246,0.25),transparent),radial-gradient(900px_500px_at_110%_10%,rgba(236,72,153,0.25),transparent),#0b0b11]">
      <TopNav
        onToggleSidebar={() => setSidebarOpen((s) => !s)}
        query={query}
        setQuery={setQuery}
        onSearch={() => { /* already reacts to input */ }}
        sort={sort}
        setSort={setSort}
      />

      <div className="mx-auto max-w-[1600px] px-4 sm:px-6 py-6 grid grid-cols-1 lg:grid-cols-[256px_1fr] gap-6">
        <Sidebar open={sidebarOpen} />

        <main>
          {!selected ? (
            <>
              <div className="flex items-end justify-between mb-4">
                <div>
                  <h1 className="text-2xl font-semibold">Recommended</h1>
                  <p className="text-white/60 text-sm">Curated for your highly specific but immaculate taste.</p>
                </div>
              </div>

              <VideoGrid videos={list} onOpen={(v) => setSelected(v)} />
            </>
          ) : (
            <PlayerView video={selected} onBack={() => setSelected(null)} onSelect={setSelected} />
          )}
        </main>
      </div>

      <footer className="px-6 py-10 text-center text-sm text-white/60">
        <p>
          Built with ❤️ for demos. OurTube is a UI clone — plug in your backend (YouTube API, Invidious,
          or your own content pipeline) when you're ready.
        </p>
      </footer>
    </div>
  );
}

// Tailwind utilities for nicer scrollbars (optional)
// Add to your global CSS if you like
// .no-scrollbar::-webkit-scrollbar { display: none; }
// .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
