"use client"

import { useState } from "react"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Cpu, BookOpen, Play, Clock, Wrench, Zap, Shield, Search, CheckCircle, ArrowLeft, Upload } from "lucide-react"
import { type PerformanceCategory, performanceCategories } from "@/lib/mock-data"

const buildGuides = [
  {
    id: "pc-assembly-guide",
    title: "Complete PC Assembly Guide",
    description:
      "Step-by-step guide for building your PC from scratch with detailed visuals and instructions. Perfect for beginners!",
    difficulty: "Beginner",
    duration: "2-3 hours",
    views: "0",
    category: "Setup",
    performanceCategory: "all" as PerformanceCategory,
    image: "/1st.png",
    steps: 12,
    tools: ["Screwdriver (magnetic tip)", "Thermal paste", "Anti-static wrist strap", "Motherboard manual"],
    estimatedCost: "₱44,000-66,000",
    tags: ["guide"],
  },
  {
    id: "pc-first-boot-setup",
    title: "PC First Boot & Setup Guide",
    description:
      "Learn how to safely boot your newly built PC, configure BIOS, install Windows, and set up essential drivers",
    difficulty: "Beginner",
    duration: "45-60 minutes",
    views: "0",
    category: "Setup",
    performanceCategory: "all" as PerformanceCategory,
    image: "/boot-guide.png",
    steps: 13,
    tools: ["USB flash drive (8GB+)", "Internet connection"],
    estimatedCost: "Free",
    tags: ["setup", "bios", "windows"],
  },
  {
    id: "budget-office-pc",
    title: "Budget Office PC Build",
    description: "Build an efficient and affordable PC for office work, web browsing, and basic productivity tasks",
    difficulty: "Beginner",
    duration: "2-3 hours",
    views: "0",
    category: "Office",
    performanceCategory: "office" as PerformanceCategory,
    image: "/budget-office-computer.jpg",
    steps: 6,
    tools: ["Screwdriver (magnetic tip)", "Thermal paste", "Anti-static wrist strap", "Motherboard manual"],
    estimatedCost: "₱22,000-33,000",
    tags: ["budget", "office"],
  },
  {
    id: "budget-gaming-build",
    title: "Best 700$ Gaming PC Build Guide",
    description: "An excellent build for 1080p gaming and you can stream to twitch or youtube",
    difficulty: "Beginner",
    duration: "2-3 hours",
    views: "0",
    category: "Gaming",
    performanceCategory: "gaming" as PerformanceCategory,
    image: "/gaming-pc-build-guide.png",
    steps: 9,
    tools: ["Screwdriver (magnetic tip)", "Thermal paste", "Anti-static wrist strap", "Motherboard manual"],
    estimatedCost: "₱82,500-137,500",
    tags: ["budget", "gaming"],
  },
]

const quickTips = [
  {
    icon: Wrench,
    title: "Essential Tools",
    description: "What you need before starting your build",
    tips: ["Phillips head screwdriver", "Anti-static wrist strap", "Good lighting", "Clean workspace"],
  },
  {
    icon: Zap,
    title: "Safety First",
    description: "Protect your components from static damage",
    tips: ["Ground yourself regularly", "Work on hard surfaces", "Avoid carpeted areas", "Handle components by edges"],
  },
  {
    icon: Shield,
    title: "Cable Management",
    description: "Keep your build clean and improve airflow",
    tips: [
      "Plan cable routes first",
      "Use zip ties sparingly",
      "Route behind motherboard tray",
      "Leave room for airflow",
    ],
  },
]

export default function GuidesPage() {
  const [searchTerm, setSearchTerm] = useState("")
  const [selectedPerformanceCategory, setSelectedPerformanceCategory] = useState<PerformanceCategory>("all")
  const [selectedDifficulty, setSelectedDifficulty] = useState("all")
  const [sortBy, setSortBy] = useState("popular")

  const getFilteredGuides = () => {
    const filtered = buildGuides.filter((guide) => {
      const matchesSearch =
        guide.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
        guide.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
        guide.tags.some((tag) => tag.toLowerCase().includes(searchTerm.toLowerCase()))

      const matchesPerformanceCategory = selectedPerformanceCategory === "all" || guide.performanceCategory === selectedPerformanceCategory
      const matchesDifficulty = selectedDifficulty === "all" || guide.difficulty.toLowerCase() === selectedDifficulty

      return matchesSearch && matchesPerformanceCategory && matchesDifficulty
    })

    // Sort guides
    switch (sortBy) {
      case "newest":
        return filtered.sort((a, b) => new Date(b.lastUpdated).getTime() - new Date(a.lastUpdated).getTime())
      case "rating":
        return filtered.sort((a, b) => b.rating - a.rating)
      case "duration":
        return filtered.sort((a, b) => a.duration.localeCompare(b.duration))
      default: // popular
        return filtered.sort(
          (a, b) => Number.parseInt(b.views.replace("k", "000")) - Number.parseInt(a.views.replace("k", "000")),
        )
    }
  }

  const filteredGuides = getFilteredGuides()

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-900 dark:to-slate-800">
      <div className="container mx-auto px-4 py-8 max-w-6xl">
        {/* Top bar: back + submit */}
        <div className="flex flex-wrap items-center justify-between gap-4 mb-8">
          <Link href="/">
            <Button variant="ghost" size="sm" className="text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white">
              <ArrowLeft className="h-4 w-4 mr-2" />
              Back to Home
            </Button>
          </Link>
          <Link href="/guides/submit">
            <Button size="sm" className="bg-blue-500 hover:bg-blue-600 text-white">
              <Upload className="h-4 w-4 mr-2" />
              Submit Guide
            </Button>
          </Link>
        </div>

        {/* Page Header */}
        <div className="text-center mb-10">
          <h1 className="text-3xl md:text-4xl font-bold text-slate-900 dark:text-white mb-3">Build Guides</h1>
          <p className="text-lg text-slate-600 dark:text-slate-400 max-w-2xl mx-auto mb-4">
            Step-by-step tutorials to help you build your perfect PC with confidence
          </p>
          <div className="inline-flex items-center gap-2 rounded-full bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300 px-4 py-2 text-sm">
            <BookOpen className="h-4 w-4" />
            <span>{buildGuides.length} guides available</span>
          </div>
        </div>

        {/* Quick Tips — blue accent cards */}
        <div className="grid md:grid-cols-3 gap-6 mb-10">
          {quickTips.map((tip, index) => (
            <Card
              key={index}
              className="border-slate-200 dark:border-slate-700 border-l-4 border-l-blue-500 bg-white dark:bg-slate-800/50 hover:shadow-md transition-shadow"
            >
              <CardHeader className="pb-2">
                <div className="rounded-lg bg-blue-500/10 w-fit p-2.5 mb-2">
                  <tip.icon className="h-10 w-10 text-blue-600 dark:text-blue-400" />
                </div>
                <CardTitle className="text-lg text-slate-900 dark:text-white">{tip.title}</CardTitle>
                <CardDescription className="text-slate-600 dark:text-slate-400">{tip.description}</CardDescription>
              </CardHeader>
              <CardContent className="pt-0">
                <ul className="space-y-2 text-sm text-slate-600 dark:text-slate-400">
                  {tip.tips.map((tipItem, tipIndex) => (
                    <li key={tipIndex} className="flex items-center gap-2">
                      <CheckCircle className="h-4 w-4 text-emerald-500 flex-shrink-0" />
                      {tipItem}
                    </li>
                  ))}
                </ul>
              </CardContent>
            </Card>
          ))}
        </div>

        {/* Search & filters — blue-accent panel */}
        <div className="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800/30 p-4 mb-8">
          <p className="text-sm font-medium text-slate-700 dark:text-slate-300 mb-3">Search & filters</p>
          <div className="flex flex-col lg:flex-row gap-3">
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
              <Input
                placeholder="Search guides, topics, or tags..."
                className="pl-10 border-slate-200 dark:border-slate-600 focus-visible:ring-blue-500 focus-visible:border-blue-500"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            <div className="flex flex-wrap gap-2">
              <Select
                value={selectedPerformanceCategory}
                onValueChange={(value) => setSelectedPerformanceCategory(value as PerformanceCategory)}
              >
                <SelectTrigger className="w-full sm:w-48 border-slate-200 dark:border-slate-600 focus:ring-blue-500 focus:border-blue-500 data-[state=open]:border-blue-500 data-[state=open]:ring-2 data-[state=open]:ring-blue-500/20">
                  <div className="w-full flex flex-col text-left">
                    <span className="font-medium truncate">
                      {selectedPerformanceCategory && performanceCategories[selectedPerformanceCategory]
                        ? performanceCategories[selectedPerformanceCategory].name
                        : "Category"}
                    </span>
                    {selectedPerformanceCategory && performanceCategories[selectedPerformanceCategory] && (
                      <span className="text-xs text-slate-500 truncate">
                        {performanceCategories[selectedPerformanceCategory].description}
                      </span>
                    )}
                  </div>
                </SelectTrigger>
                <SelectContent>
                  {Object.entries(performanceCategories).map(([key, category]) => (
                    <SelectItem key={key} value={key}>
                      <div className="flex flex-col">
                        <span className="font-medium">{category.name}</span>
                        <span className="text-xs text-slate-500 truncate">{category.description}</span>
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Select value={selectedDifficulty} onValueChange={setSelectedDifficulty}>
                <SelectTrigger className="w-full sm:w-36 border-slate-200 dark:border-slate-600 focus:ring-blue-500 focus:border-blue-500 data-[state=open]:border-blue-500 data-[state=open]:ring-2 data-[state=open]:ring-blue-500/20">
                  <SelectValue placeholder="Difficulty" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Levels</SelectItem>
                  <SelectItem value="beginner">Beginner</SelectItem>
                  <SelectItem value="intermediate">Intermediate</SelectItem>
                  <SelectItem value="advanced">Advanced</SelectItem>
                </SelectContent>
              </Select>
              <Select value={sortBy} onValueChange={setSortBy}>
                <SelectTrigger className="w-full sm:w-36 border-slate-200 dark:border-slate-600 focus:ring-blue-500 focus:border-blue-500 data-[state=open]:border-blue-500 data-[state=open]:ring-2 data-[state=open]:ring-blue-500/20">
                  <SelectValue placeholder="Sort by" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="popular">Most Popular</SelectItem>
                  <SelectItem value="newest">Newest</SelectItem>
                  <SelectItem value="rating">Highest Rated</SelectItem>
                  <SelectItem value="duration">Duration</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </div>

        {/* All Guides */}
        <div className="mb-8">
          <div className="flex flex-wrap items-center justify-between gap-4 mb-6">
            <h2 className="text-2xl font-bold text-slate-900 dark:text-white">
              {selectedPerformanceCategory === "all"
                ? "All Guides"
                : `${performanceCategories[selectedPerformanceCategory]?.name ?? "Category"} Guides`}
            </h2>
            <span className="text-sm text-slate-600 dark:text-slate-400">
              {filteredGuides.length} guide{filteredGuides.length !== 1 ? "s" : ""} found
            </span>
          </div>

          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
            {filteredGuides.map((guide) => (
              <Card
                key={guide.id}
                className="border-slate-200 dark:border-slate-700 overflow-hidden hover:shadow-lg hover:border-blue-200 dark:hover:border-blue-900/50 transition-all duration-200 group"
              >
                <div className="relative">
                  <img
                    src={guide.image || "/placeholder.svg"}
                    alt={guide.title}
                    className="w-full h-44 object-cover"
                  />
                  <div className="absolute top-3 left-3 flex flex-wrap gap-2">
                    <Badge className="bg-blue-500 hover:bg-blue-600 text-white border-0">
                      {performanceCategories[guide.performanceCategory]?.name ?? guide.category}
                    </Badge>
                    <Badge
                      variant={guide.difficulty === "Beginner" ? "secondary" : guide.difficulty === "Advanced" ? "destructive" : "default"}
                      className="font-medium"
                    >
                      {guide.difficulty}
                    </Badge>
                  </div>
                </div>
                <CardHeader className="pb-2">
                  <CardTitle className="text-lg leading-tight group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors line-clamp-2">
                    <Link href={`/guides/${guide.id}`} className="focus:outline-none">{guide.title}</Link>
                  </CardTitle>
                  <CardDescription className="line-clamp-2 text-slate-600 dark:text-slate-400">{guide.description}</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4 pt-0">
                  <div className="grid grid-cols-2 gap-x-4 gap-y-2 text-sm text-slate-600 dark:text-slate-400">
                    <div className="flex items-center gap-1.5">
                      <Clock className="h-4 w-4 text-slate-400" />
                      <span>{guide.duration}</span>
                    </div>
                    <div className="flex items-center gap-1.5">
                      <BookOpen className="h-4 w-4 text-slate-400" />
                      <span>{guide.steps} steps</span>
                    </div>
                    <div className="flex items-center gap-1.5">
                      <Wrench className="h-4 w-4 text-slate-400" />
                      <span>{guide.tools.length} tools</span>
                    </div>
                  </div>
                  <div className="flex flex-wrap gap-1.5">
                    {guide.tags.slice(0, 3).map((tag) => (
                      <Badge key={tag} variant="outline" className="text-xs font-normal">
                        {tag}
                      </Badge>
                    ))}
                  </div>
                  <div className="pt-3 border-t border-slate-100 dark:border-slate-700 flex justify-end">
                    <Button size="sm" asChild className="bg-blue-500 hover:bg-blue-600 text-white">
                      <Link href={`/guides/${guide.id}`}>
                        <Play className="h-4 w-4 mr-2" />
                        Start Guide
                      </Link>
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>

          {filteredGuides.length === 0 && (
            <div className="rounded-2xl border border-dashed border-slate-300 dark:border-slate-600 bg-slate-50/50 dark:bg-slate-800/30 py-16 px-6 text-center">
              <div className="rounded-full bg-slate-200/80 dark:bg-slate-700/80 p-4 w-fit mx-auto mb-4">
                <BookOpen className="h-10 w-10 text-slate-500 dark:text-slate-400" />
              </div>
              <h3 className="text-xl font-semibold text-slate-900 dark:text-white mb-2">No guides match your filters</h3>
              <p className="text-slate-600 dark:text-slate-400 max-w-sm mx-auto mb-6">
                Try different search terms or clear the category and difficulty filters.
              </p>
              <Button
                className="bg-blue-500 hover:bg-blue-600 text-white"
                onClick={() => {
                  setSearchTerm("")
                  setSelectedPerformanceCategory("all")
                  setSelectedDifficulty("all")
                }}
              >
                Clear filters
              </Button>
            </div>
          )}
        </div>

        {/* CTA */}
        <div className="text-center py-12 px-6 rounded-2xl border-2 border-blue-200 dark:border-blue-900/50 bg-blue-50/50 dark:bg-blue-900/10">
          <h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-3">Ready to start building?</h2>
          <p className="text-slate-600 dark:text-slate-400 max-w-xl mx-auto mb-6">
            Use the PC Builder to pick compatible parts and get real-time compatibility checking.
          </p>
          <Button size="lg" asChild className="bg-blue-500 hover:bg-blue-600 text-white">
            <Link href="/builder">
              <Cpu className="h-5 w-5 mr-2" />
              Open PC Builder
            </Link>
          </Button>
        </div>
      </div>
    </div>
  )
}