"use client"

import { useState } from "react"
import Link from "next/link"
import Image from "next/image"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  Search,
  Star,
  Clock,
  Plus,
  Copy,
  Globe,
  BarChart3,
  Zap,
  Code,
  ArrowRight,
  Download,
  Eye,
  Heart,
  Share2,
} from "lucide-react"

interface Template {
  id: string
  title: string
  description: string
  category: string
  features: string[]
  complexity: number
  timeEstimate: string
  techStack: string[]
  popularity?: number
  lastUpdated?: string
  downloads?: number
  likes?: number
  author?: string
  isPublic?: boolean
  preview?: string
}

export function TemplatesPage() {
  const [activeTab, setActiveTab] = useState("browse")
  const [selectedCategory, setSelectedCategory] = useState("all")
  const [searchQuery, setSearchQuery] = useState("")
  const [sortBy, setSortBy] = useState("popularity")

  const templates: Template[] = [
    // Marketing Templates
    {
      id: "marketing-website",
      title: "Marketing Website",
      description: "Professional marketing site with CMS and lead generation",
      category: "marketing",
      features: ["Content Management", "Contact Forms", "SEO Optimization", "Analytics Integration"],
      complexity: 2,
      timeEstimate: "1-2 weeks",
      techStack: ["Next.js", "Sanity CMS", "Tailwind CSS", "Vercel"],
      popularity: 95,
      lastUpdated: "2024-01-15",
      downloads: 1250,
      likes: 89,
      author: "Codenuk Team",
      isPublic: true,
      preview: "/marketing-website-preview.png",
    },
    {
      id: "landing-page",
      title: "Landing Page",
      description: "High-converting landing page with A/B testing capabilities",
      category: "marketing",
      features: ["A/B Testing", "Conversion Tracking", "Lead Capture", "Mobile Optimization"],
      complexity: 2,
      timeEstimate: "3-5 days",
      techStack: ["Next.js", "Tailwind CSS", "Google Analytics", "Mailchimp"],
      popularity: 88,
      lastUpdated: "2024-01-10",
      downloads: 980,
      likes: 76,
      author: "Codenuk Team",
      isPublic: true,
      preview: "/landing-page-preview.png",
    },
    {
      id: "blog-platform",
      title: "Blog Platform",
      description: "Content-rich blog with SEO optimization and social sharing",
      category: "marketing",
      features: ["Content Management", "SEO Tools", "Social Sharing", "Comment System"],
      complexity: 3,
      timeEstimate: "1-2 weeks",
      techStack: ["Next.js", "MDX", "Tailwind CSS", "Disqus"],
      popularity: 82,
      lastUpdated: "2024-01-12",
      downloads: 756,
      likes: 64,
      author: "Community",
      isPublic: true,
      preview: "/blog-platform-preview.png",
    },
    // Software Templates
    {
      id: "saas-platform",
      title: "SaaS Platform",
      description: "Complete SaaS application with user management, billing, and analytics",
      category: "software",
      features: ["User Authentication", "Payment Processing", "Analytics Integration", "API Management"],
      complexity: 5,
      timeEstimate: "4-6 weeks",
      techStack: ["Next.js", "PostgreSQL", "Stripe", "NextAuth.js"],
      popularity: 92,
      lastUpdated: "2024-01-15",
      downloads: 2100,
      likes: 156,
      author: "Codenuk Team",
      isPublic: true,
      preview: "/saas-platform-preview.png",
    },
    {
      id: "dashboard-app",
      title: "Analytics Dashboard",
      description: "Data visualization dashboard with real-time updates",
      category: "software",
      features: ["Data Visualization", "Real-time Updates", "User Authentication", "Export Features"],
      complexity: 4,
      timeEstimate: "3-4 weeks",
      techStack: ["Next.js", "Chart.js", "WebSockets", "PostgreSQL"],
      popularity: 89,
      lastUpdated: "2024-01-14",
      downloads: 1890,
      likes: 134,
      author: "Community",
      isPublic: true,
      preview: "/analytics-dashboard-preview.png",
    },
    // SEO Templates
    {
      id: "seo-optimized-blog",
      title: "SEO-Optimized Blog",
      description: "Blog platform with advanced SEO features and schema markup",
      category: "seo",
      features: ["Schema Markup", "Meta Optimization", "Sitemap Generation", "Performance Optimization"],
      complexity: 3,
      timeEstimate: "2-3 weeks",
      techStack: ["Next.js", "SEO Tools", "Schema.org", "Google Search Console"],
      popularity: 90,
      lastUpdated: "2024-01-15",
      downloads: 1456,
      likes: 98,
      author: "SEO Expert",
      isPublic: true,
      preview: "/seo-blog-preview.png",
    },
  ]

  const categories = [
    { id: "all", name: "All Templates", icon: Globe, count: templates.length },
    {
      id: "marketing",
      name: "Marketing",
      icon: Zap,
      count: templates.filter((t) => t.category === "marketing").length,
    },
    { id: "software", name: "Software", icon: Code, count: templates.filter((t) => t.category === "software").length },
    { id: "seo", name: "SEO", icon: BarChart3, count: templates.filter((t) => t.category === "seo").length },
  ]

  const filteredTemplates = templates.filter((template) => {
    const matchesCategory = selectedCategory === "all" || template.category === selectedCategory
    const matchesSearch =
      template.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      template.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
      template.features.some((feature) => feature.toLowerCase().includes(searchQuery.toLowerCase()))
    return matchesCategory && matchesSearch
  })

  const sortedTemplates = [...filteredTemplates].sort((a, b) => {
    switch (sortBy) {
      case "popularity":
        return (b.popularity || 0) - (a.popularity || 0)
      case "downloads":
        return (b.downloads || 0) - (a.downloads || 0)
      case "recent":
        return new Date(b.lastUpdated || "").getTime() - new Date(a.lastUpdated || "").getTime()
      case "likes":
        return (b.likes || 0) - (a.likes || 0)
      default:
        return 0
    }
  })

  const getComplexityColor = (complexity: number) => {
    if (complexity <= 2) return "bg-emerald-900/40 text-emerald-300 border border-emerald-800"
    if (complexity <= 3) return "bg-amber-900/40 text-amber-300 border border-amber-800"
    return "bg-rose-900/40 text-rose-300 border border-rose-800"
  }

  const getComplexityLabel = (complexity: number) => {
    if (complexity <= 2) return "Simple"
    if (complexity <= 3) return "Moderate"
    return "Complex"
  }

  const TemplateCard = ({ template }: { template: Template }) => (
    <Card className="group hover:shadow-md transition-all bg-white/5 border border-white/10">
      <div className="relative">
        <Image
          src={template.preview || "/placeholder.svg"}
          alt={`${template.title} preview`}
          width={400}
          height={192}
          className="w-full h-48 object-cover rounded-t-lg"
        />
        <div className="absolute top-3 right-3 flex space-x-2">
          <Button size="sm" variant="secondary" className="opacity-0 group-hover:opacity-100 transition-opacity bg-white/10 text-white hover:bg-white/20">
            <Eye className="h-4 w-4" />
          </Button>
          <Button size="sm" variant="secondary" className="opacity-0 group-hover:opacity-100 transition-opacity bg-white/10 text-white hover:bg-white/20">
            <Heart className="h-4 w-4" />
          </Button>
        </div>
      </div>

      <CardHeader className="pb-3">
        <div className="flex items-start justify-between">
          <div className="space-y-2 flex-1">
            <CardTitle className="text-lg text-white group-hover:text-orange-400 transition-colors">{template.title}</CardTitle>
            <div className="flex items-center space-x-2">
              <Badge className={getComplexityColor(template.complexity)}>{getComplexityLabel(template.complexity)}</Badge>
              <div className="flex items-center space-x-1 text-sm text-white/60">
                <Star className="h-4 w-4 text-amber-400 fill-current" />
                <span>{template.popularity}%</span>
              </div>
            </div>
          </div>
        </div>
        <p className="text-white/70 text-sm">{template.description}</p>
      </CardHeader>

      <CardContent className="space-y-4 text-white/80">
        <div className="flex items-center justify-between text-sm">
          <div className="flex items-center space-x-1">
            <Clock className="h-4 w-4 text-orange-400" />
            <span>{template.timeEstimate}</span>
          </div>
          <div className="flex items-center space-x-1">
            <Download className="h-4 w-4" />
            <span>{template.downloads}</span>
          </div>
        </div>

        <div className="space-y-3">
          <div>
            <h4 className="font-medium text-sm text-white mb-2">Features:</h4>
            <div className="flex flex-wrap gap-1">
              {template.features.slice(0, 2).map((feature, index) => (
                <Badge key={index} variant="outline" className="text-xs bg-white/5 border-white/10 text-white/80">
                  {feature}
                </Badge>
              ))}
              {template.features.length > 2 && (
                <Badge variant="outline" className="text-xs bg-white/5 border-white/10 text-white/70">
                  +{template.features.length - 2} more
                </Badge>
              )}
            </div>
          </div>

          <div>
            <h4 className="font-medium text-sm text-white mb-2">Tech Stack:</h4>
            <div className="flex flex-wrap gap-1">
              {template.techStack.slice(0, 3).map((tech, index) => (
                <Badge key={index} variant="secondary" className="text-xs bg-white/10 text-white">
                  {tech}
                </Badge>
              ))}
            </div>
          </div>
        </div>

        <div className="flex space-x-2 pt-2">
          <Button className="flex-1">
            Use Template
            <ArrowRight className="ml-2 h-4 w-4" />
          </Button>
          <Button variant="outline" size="sm" className="border-white/20 text-white hover:bg-white/10">
            <Copy className="h-4 w-4" />
          </Button>
          <Button variant="outline" size="sm" className="border-white/20 text-white hover:bg-white/10">
            <Share2 className="h-4 w-4" />
          </Button>
        </div>

        <div className="flex items-center justify-between text-xs text-white/60 pt-2 border-t border-white/10">
          <span>by {template.author}</span>
          <span>{template.lastUpdated}</span>
        </div>
      </CardContent>
    </Card>
  )

  return (
    <div className="min-h-screen bg-black">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 text-white">
        <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-8">
          <div className="flex items-center justify-between">
            <TabsList className="grid w-full max-w-md grid-cols-3 bg-white/5 border border-white/10">
              <TabsTrigger value="browse">Browse Templates</TabsTrigger>
              <TabsTrigger value="my-templates">My Templates</TabsTrigger>
              <TabsTrigger value="favorites">Favorites</TabsTrigger>
            </TabsList>

            <div className="flex items-center space-x-4">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-white/40 h-4 w-4" />
                <Input
                  placeholder="Search templates..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-10 w-80 bg-white/5 border-white/10 text-white placeholder:text-white/40"
                />
              </div>
              <select
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value)}
                className="px-3 py-2 border border-white/10 bg-white/5 rounded-md text-sm text-white"
              >
                <option value="popularity">Most Popular</option>
                <option value="downloads">Most Downloaded</option>
                <option value="recent">Recently Updated</option>
                <option value="likes">Most Liked</option>
              </select>
            </div>
          </div>

          <TabsContent value="browse" className="space-y-8">
            {/* Category Filters */}
            <div className="flex flex-wrap gap-4">
              {categories.map((category) => {
                const Icon = category.icon
                const active = selectedCategory === category.id
                return (
                  <button
                    key={category.id}
                    onClick={() => setSelectedCategory(category.id)}
                    className={`flex items-center space-x-2 px-4 py-2 rounded-lg border transition-all ${
                      active
                        ? "bg-orange-500 text-black border-orange-500"
                        : "bg-white/5 text-white/80 border-white/10 hover:bg-white/10"
                    }`}
                  >
                    <Icon className="h-4 w-4" />
                    <span className="font-medium">{category.name}</span>
                    <Badge variant="secondary" className="ml-1 bg-white/10 text-white">
                      {category.count}
                    </Badge>
                  </button>
                )
              })}
            </div>

            {/* Templates Grid */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
              {sortedTemplates.map((template) => (
                <TemplateCard key={template.id} template={template} />
              ))}
            </div>

            {/* Results Summary */}
            <div className="text-center py-8">
              <p className="text-white/70">
                Showing {sortedTemplates.length} template{sortedTemplates.length !== 1 ? "s" : ""}
                {searchQuery && ` matching "${searchQuery}"`}
              </p>
            </div>
          </TabsContent>

          <TabsContent value="my-templates" className="space-y-8">
            <div className="text-center py-20">
              <Plus className="h-16 w-16 text-white/40 mx-auto mb-6" />
              <h3 className="text-2xl font-semibold text-white mb-3">No Templates Yet</h3>
              <p className="text-white/60 mb-6 max-w-md mx-auto">
                Create your first template to get started. Templates you create will appear here.
              </p>
              <Button>
                <Plus className="mr-2 h-5 w-5" />
                Create Your First Template
              </Button>
            </div>
          </TabsContent>

          <TabsContent value="favorites" className="space-y-8">
            <div className="text-center py-20">
              <Heart className="h-16 w-16 text-white/40 mx-auto mb-6" />
              <h3 className="text-2xl font-semibold text-white mb-3">No Favorites Yet</h3>
              <p className="text-white/60 mb-6 max-w-md mx-auto">
                Heart templates you like to save them here for quick access later.
              </p>
              <Button variant="outline" onClick={() => setActiveTab("browse")} className="text-white border-white/20 hover:bg-white/10">
                Browse Templates
              </Button>
            </div>
          </TabsContent>
        </Tabs>
      </div>
    </div>
  )
}
