"use client"

import type React from "react"

import { useState, useRef } from "react"
import Link from "next/link"
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 {
  Search,
  Plus,
  Trash2,
  GripVertical,
  Database,
  Shield,
  CreditCard,
  BarChart3,
  Bell,
  Mail,
  Globe,
  Smartphone,
  Zap,
  Settings,
  FileText,
  ImageIcon,
  Video,
  MessageSquare,
  Star,
  Code,
  Palette,
  Layers,
  Save,
  Download,
} from "lucide-react"
import { ArrowRight } from "lucide-react" // Added import for ArrowRight

interface Feature {
  id: string
  name: string
  description: string
  category: string
  icon: any
  complexity: number
  timeImpact: string
  dependencies: string[]
  conflicts: string[]
  techStack: string[]
  businessQuestions: string[]
  isCore?: boolean
  isPopular?: boolean
}

interface SelectedFeature extends Feature {
  order: number
  customConfig?: any
}

export function FeaturesPage() {
  const [activeTab, setActiveTab] = useState("browse")
  const [selectedCategory, setSelectedCategory] = useState("all")
  const [searchQuery, setSearchQuery] = useState("")
  const [selectedFeatures, setSelectedFeatures] = useState<SelectedFeature[]>([])
  const [draggedFeature, setDraggedFeature] = useState<Feature | null>(null)
  const [dragOverIndex, setDragOverIndex] = useState<number | null>(null)
  const dropZoneRef = useRef<HTMLDivElement>(null)

  const features: Feature[] = [
    // Core Features
    {
      id: "user-auth",
      name: "User Authentication",
      description: "Secure user registration, login, and session management",
      category: "core",
      icon: Shield,
      complexity: 3,
      timeImpact: "2-3 days",
      dependencies: [],
      conflicts: [],
      techStack: ["NextAuth.js", "JWT", "OAuth"],
      businessQuestions: [
        "How many users do you expect in the first year?",
        "Do you need social login (Google, Facebook)?",
        "Will you have different user roles?",
      ],
      isCore: true,
      isPopular: true,
    },
    {
      id: "database",
      name: "Database Integration",
      description: "Data storage and management system",
      category: "core",
      icon: Database,
      complexity: 4,
      timeImpact: "3-5 days",
      dependencies: [],
      conflicts: [],
      techStack: ["PostgreSQL", "Prisma", "Redis"],
      businessQuestions: [
        "What's your expected data volume?",
        "Do you need real-time data updates?",
        "What's your data backup strategy?",
      ],
      isCore: true,
      isPopular: true,
    },
    {
      id: "api-management",
      name: "API Management",
      description: "RESTful API with rate limiting and documentation",
      category: "core",
      icon: Code,
      complexity: 3,
      timeImpact: "2-4 days",
      dependencies: ["database"],
      conflicts: [],
      techStack: ["Next.js API Routes", "Swagger", "Rate Limiting"],
      businessQuestions: [
        "Will you have external API integrations?",
        "Do you need API versioning?",
        "What's your expected API call volume?",
      ],
      isCore: true,
    },

    // Business Features
    {
      id: "payment-processing",
      name: "Payment Processing",
      description: "Secure payment handling with multiple providers",
      category: "business",
      icon: CreditCard,
      complexity: 5,
      timeImpact: "1-2 weeks",
      dependencies: ["user-auth", "database"],
      conflicts: [],
      techStack: ["Stripe", "PayPal", "Webhook Handling"],
      businessQuestions: [
        "What payment methods do you need?",
        "What's your expected transaction volume?",
        "Do you need subscription billing?",
      ],
      isPopular: true,
    },
    {
      id: "analytics",
      name: "Analytics & Tracking",
      description: "User behavior tracking and business metrics",
      category: "business",
      icon: BarChart3,
      complexity: 3,
      timeImpact: "2-3 days",
      dependencies: [],
      conflicts: [],
      techStack: ["Google Analytics", "Mixpanel", "Custom Events"],
      businessQuestions: [
        "What metrics are most important to track?",
        "Do you need real-time analytics?",
        "What's your privacy policy regarding data?",
      ],
      isPopular: true,
    },
    {
      id: "notifications",
      name: "Notification System",
      description: "Email, SMS, and push notifications",
      category: "business",
      icon: Bell,
      complexity: 4,
      timeImpact: "3-5 days",
      dependencies: ["user-auth"],
      conflicts: [],
      techStack: ["SendGrid", "Twilio", "Push API"],
      businessQuestions: [
        "What types of notifications do you need?",
        "How frequently will you send notifications?",
        "Do you need notification preferences?",
      ],
    },

    // UI/UX Features
    {
      id: "responsive-design",
      name: "Responsive Design",
      description: "Mobile-first responsive layout",
      category: "ui",
      icon: Smartphone,
      complexity: 2,
      timeImpact: "1-2 days",
      dependencies: [],
      conflicts: [],
      techStack: ["Tailwind CSS", "CSS Grid", "Flexbox"],
      businessQuestions: ["What devices will your users primarily use?", "Do you need a mobile app later?"],
      isCore: true,
    },
    {
      id: "dark-mode",
      name: "Dark Mode",
      description: "Toggle between light and dark themes",
      category: "ui",
      icon: Palette,
      complexity: 2,
      timeImpact: "1 day",
      dependencies: ["responsive-design"],
      conflicts: [],
      techStack: ["CSS Variables", "Theme Provider"],
      businessQuestions: ["Is this important for your user base?"],
    },
    {
      id: "animations",
      name: "Animations & Transitions",
      description: "Smooth animations and micro-interactions",
      category: "ui",
      icon: Zap,
      complexity: 3,
      timeImpact: "2-3 days",
      dependencies: ["responsive-design"],
      conflicts: [],
      techStack: ["Framer Motion", "CSS Animations"],
      businessQuestions: ["What's your performance priority?"],
    },

    // Content Features
    {
      id: "content-management",
      name: "Content Management",
      description: "CMS for managing dynamic content",
      category: "content",
      icon: FileText,
      complexity: 4,
      timeImpact: "1 week",
      dependencies: ["database"],
      conflicts: [],
      techStack: ["Sanity", "Strapi", "MDX"],
      businessQuestions: ["Who will manage content?", "How often will content change?"],
    },
    {
      id: "media-upload",
      name: "Media Upload",
      description: "File and image upload with optimization",
      category: "content",
      icon: ImageIcon, // Updated from Image to ImageIcon
      complexity: 3,
      timeImpact: "2-3 days",
      dependencies: ["database"],
      conflicts: [],
      techStack: ["Cloudinary", "AWS S3", "Image Optimization"],
      businessQuestions: ["What file types do you need?", "What's your storage budget?"],
    },
    {
      id: "video-streaming",
      name: "Video Streaming",
      description: "Video upload and streaming capabilities",
      category: "content",
      icon: Video,
      complexity: 5,
      timeImpact: "1-2 weeks",
      dependencies: ["media-upload"],
      conflicts: [],
      techStack: ["Vimeo API", "YouTube API", "Video.js"],
      businessQuestions: ["What video quality do you need?", "Expected video volume?"],
    },

    // Communication Features
    {
      id: "chat-system",
      name: "Real-time Chat",
      description: "Live messaging and communication",
      category: "communication",
      icon: MessageSquare,
      complexity: 4,
      timeImpact: "1 week",
      dependencies: ["user-auth", "database"],
      conflicts: [],
      techStack: ["WebSockets", "Socket.io", "Real-time DB"],
      businessQuestions: ["How many concurrent users?", "Do you need group chats?"],
    },
    {
      id: "email-integration",
      name: "Email Integration",
      description: "Email sending and template management",
      category: "communication",
      icon: Mail,
      complexity: 3,
      timeImpact: "2-3 days",
      dependencies: [],
      conflicts: [],
      techStack: ["SendGrid", "Mailgun", "Email Templates"],
      businessQuestions: ["What types of emails will you send?", "Expected email volume?"],
    },

    // Advanced Features
    {
      id: "ai-integration",
      name: "AI Integration",
      description: "Machine learning and AI-powered features",
      category: "advanced",
      icon: Layers,
      complexity: 5,
      timeImpact: "1-3 weeks",
      dependencies: ["api-management"],
      conflicts: [],
      techStack: ["OpenAI API", "TensorFlow", "Custom Models"],
      businessQuestions: ["What AI capabilities do you need?", "What's your AI budget?", "Do you have training data?"],
    },
    {
      id: "real-time",
      name: "Real-time Features",
      description: "Live updates and collaboration",
      category: "advanced",
      icon: Zap,
      complexity: 4,
      timeImpact: "1 week",
      dependencies: ["database"],
      conflicts: [],
      techStack: ["WebSockets", "Socket.io", "Redis Pub/Sub"],
      businessQuestions: ["How many concurrent users?", "What needs to be real-time?"],
    },
  ]

  const categories = [
    { id: "all", name: "All Features", icon: Globe, count: features.length },
    { id: "core", name: "Core", icon: Settings, count: features.filter((f) => f.category === "core").length },
    {
      id: "business",
      name: "Business",
      icon: BarChart3,
      count: features.filter((f) => f.category === "business").length,
    },
    { id: "ui", name: "UI/UX", icon: Palette, count: features.filter((f) => f.category === "ui").length },
    { id: "content", name: "Content", icon: FileText, count: features.filter((f) => f.category === "content").length },
    {
      id: "communication",
      name: "Communication",
      icon: MessageSquare,
      count: features.filter((f) => f.category === "communication").length,
    },
    {
      id: "advanced",
      name: "Advanced",
      icon: Layers,
      count: features.filter((f) => f.category === "advanced").length,
    },
  ]

  const filteredFeatures = features.filter((feature) => {
    const matchesCategory = selectedCategory === "all" || feature.category === selectedCategory
    const matchesSearch =
      feature.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      feature.description.toLowerCase().includes(searchQuery.toLowerCase())
    const notAlreadySelected = !selectedFeatures.some((sf) => sf.id === feature.id)
    return matchesCategory && matchesSearch && notAlreadySelected
  })

  const getComplexityColor = (complexity: number) => {
    if (complexity <= 2) return "bg-green-100 text-green-800"
    if (complexity <= 3) return "bg-yellow-100 text-yellow-800"
    return "bg-red-100 text-red-800"
  }

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

  const handleDragStart = (feature: Feature) => {
    setDraggedFeature(feature)
  }

  const handleDragOver = (e: React.DragEvent, index?: number) => {
    e.preventDefault()
    if (typeof index === "number") {
      setDragOverIndex(index)
    }
  }

  const handleDrop = (e: React.DragEvent, index?: number) => {
    e.preventDefault()
    if (!draggedFeature) return

    const newFeature: SelectedFeature = {
      ...draggedFeature,
      order: typeof index === "number" ? index : selectedFeatures.length,
    }

    if (typeof index === "number") {
      const newFeatures = [...selectedFeatures]
      newFeatures.splice(index, 0, newFeature)
      // Update order for all features
      newFeatures.forEach((f, i) => (f.order = i))
      setSelectedFeatures(newFeatures)
    } else {
      setSelectedFeatures([...selectedFeatures, newFeature])
    }

    setDraggedFeature(null)
    setDragOverIndex(null)
  }

  const removeFeature = (featureId: string) => {
    setSelectedFeatures(selectedFeatures.filter((f) => f.id !== featureId))
  }

  const reorderFeatures = (fromIndex: number, toIndex: number) => {
    const newFeatures = [...selectedFeatures]
    const [movedFeature] = newFeatures.splice(fromIndex, 1)
    newFeatures.splice(toIndex, 0, movedFeature)
    // Update order for all features
    newFeatures.forEach((f, i) => (f.order = i))
    setSelectedFeatures(newFeatures)
  }

  const calculateTotalComplexity = () => {
    return selectedFeatures.reduce((total, feature) => total + feature.complexity, 0)
  }

  const calculateEstimatedTime = () => {
    const totalDays = selectedFeatures.reduce((total, feature) => {
      const days = feature.timeImpact.match(/(\d+)/g)?.map(Number) || [1]
      return total + Math.max(...days)
    }, 0)

    if (totalDays < 7) return `${totalDays} days`
    if (totalDays < 30) return `${Math.ceil(totalDays / 7)} weeks`
    return `${Math.ceil(totalDays / 30)} months`
  }

  const FeatureCard = ({ feature, isDraggable = true }: { feature: Feature; isDraggable?: boolean }) => {
    const Icon = feature.icon
    return (
      <Card
        className={`group hover:shadow-lg transition-all duration-300 border-2 hover:border-blue-200 ${
          isDraggable ? "cursor-grab active:cursor-grabbing" : ""
        }`}
        draggable={isDraggable}
        onDragStart={() => isDraggable && handleDragStart(feature)}
      >
        <CardHeader className="pb-3">
          <div className="flex items-start justify-between">
            <div className="flex items-center space-x-3">
              <div className="p-2 bg-blue-100 rounded-lg">
                <Icon className="h-5 w-5 text-blue-600" />
              </div>
              <div className="space-y-1">
                <CardTitle className="text-lg group-hover:text-blue-600 transition-colors">{feature.name}</CardTitle>
                <div className="flex items-center space-x-2">
                  <Badge className={getComplexityColor(feature.complexity)}>
                    {getComplexityLabel(feature.complexity)}
                  </Badge>
                  {feature.isCore && <Badge variant="secondary">Core</Badge>}
                  {feature.isPopular && (
                    <Badge variant="outline" className="text-yellow-600 border-yellow-300">
                      <Star className="h-3 w-3 mr-1 fill-current" />
                      Popular
                    </Badge>
                  )}
                </div>
              </div>
            </div>
            {isDraggable && <GripVertical className="h-5 w-5 text-gray-400 opacity-0 group-hover:opacity-100" />}
          </div>
          <p className="text-gray-600 text-sm mt-2">{feature.description}</p>
        </CardHeader>

        <CardContent className="space-y-3">
          <div className="flex items-center justify-between text-sm text-gray-500">
            <span>Time Impact: {feature.timeImpact}</span>
            <span>Complexity: {feature.complexity}/5</span>
          </div>

          <div>
            <h4 className="font-medium text-sm text-gray-700 mb-2">Tech Stack:</h4>
            <div className="flex flex-wrap gap-1">
              {feature.techStack.slice(0, 3).map((tech, index) => (
                <Badge key={index} variant="outline" className="text-xs">
                  {tech}
                </Badge>
              ))}
              {feature.techStack.length > 3 && (
                <Badge variant="outline" className="text-xs">
                  +{feature.techStack.length - 3}
                </Badge>
              )}
            </div>
          </div>

          {feature.dependencies.length > 0 && (
            <div className="p-2 bg-yellow-50 border border-yellow-200 rounded text-sm">
              <span className="font-medium text-yellow-800">Dependencies:</span>
              <span className="text-yellow-700 ml-1">
                {feature.dependencies
                  .map((depId) => {
                    const dep = features.find((f) => f.id === depId)
                    return dep?.name
                  })
                  .join(", ")}
              </span>
            </div>
          )}
        </CardContent>
      </Card>
    )
  }

  const SelectedFeatureCard = ({ feature, index }: { feature: SelectedFeature; index: number }) => {
    const Icon = feature.icon
    return (
      <Card
        className="group border-2 border-blue-200 bg-blue-50 hover:shadow-lg transition-all duration-300"
        draggable
        onDragStart={() => handleDragStart(feature)}
        onDragOver={(e) => handleDragOver(e, index)}
        onDrop={(e) => handleDrop(e, index)}
      >
        <CardContent className="p-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3">
              <GripVertical className="h-4 w-4 text-gray-400 cursor-grab" />
              <div className="p-2 bg-blue-200 rounded-lg">
                <Icon className="h-4 w-4 text-blue-700" />
              </div>
              <div>
                <h4 className="font-medium text-blue-900">{feature.name}</h4>
                <p className="text-sm text-blue-700">{feature.timeImpact}</p>
              </div>
            </div>
            <div className="flex items-center space-x-2">
              <Badge className={getComplexityColor(feature.complexity)}>{feature.complexity}</Badge>
              <Button
                size="sm"
                variant="ghost"
                onClick={() => removeFeature(feature.id)}
                className="text-red-600 hover:text-red-700 hover:bg-red-50"
              >
                <Trash2 className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50">

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Features Library */}
          <div className="lg:col-span-2 space-y-6">
            <div className="flex items-center justify-between">
              <h2 className="text-2xl font-bold text-gray-900">Features Library</h2>
              <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-gray-400 h-4 w-4" />
                  <Input
                    placeholder="Search features..."
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="pl-10 w-80"
                  />
                </div>
              </div>
            </div>

            {/* Category Filters */}
            <div className="flex flex-wrap gap-3">
              {categories.map((category) => {
                const Icon = category.icon
                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 ${
                      selectedCategory === category.id
                        ? "bg-blue-600 text-white border-blue-600"
                        : "bg-white text-gray-700 border-gray-200 hover:border-blue-300"
                    }`}
                  >
                    <Icon className="h-4 w-4" />
                    <span className="font-medium">{category.name}</span>
                    <Badge variant="secondary" className="ml-1">
                      {category.count}
                    </Badge>
                  </button>
                )
              })}
            </div>

            {/* Features Grid */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {filteredFeatures.map((feature) => (
                <FeatureCard key={feature.id} feature={feature} />
              ))}
            </div>
          </div>

          {/* Selected Features Panel */}
          <div className="lg:col-span-1">
            <Card className="sticky top-8">
              <CardHeader>
                <CardTitle className="flex items-center justify-between">
                  <span>Selected Features</span>
                  <Badge variant="secondary">{selectedFeatures.length}</Badge>
                </CardTitle>
                <p className="text-sm text-gray-600">Drag features here to build your project</p>
              </CardHeader>
              <CardContent className="space-y-4">
                {/* Project Summary */}
                <div className="p-4 bg-gray-50 rounded-lg space-y-3">
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-600">Total Complexity:</span>
                    <Badge
                      variant={
                        calculateTotalComplexity() > 20
                          ? "destructive"
                          : calculateTotalComplexity() > 15
                            ? "default"
                            : "secondary"
                      }
                    >
                      {calculateTotalComplexity()}/50
                    </Badge>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-600">Estimated Time:</span>
                    <span className="font-medium">{calculateEstimatedTime()}</span>
                  </div>
                </div>

                {/* Drop Zone */}
                <div
                  ref={dropZoneRef}
                  className={`min-h-[200px] border-2 border-dashed rounded-lg p-4 transition-all ${
                    draggedFeature
                      ? "border-blue-400 bg-blue-50"
                      : selectedFeatures.length === 0
                        ? "border-gray-300"
                        : "border-transparent"
                  }`}
                  onDragOver={handleDragOver}
                  onDrop={handleDrop}
                >
                  {selectedFeatures.length === 0 ? (
                    <div className="text-center py-12">
                      <Plus className="h-12 w-12 text-gray-400 mx-auto mb-4" />
                      <p className="text-gray-500 text-sm">
                        Drag features from the library to start building your project
                      </p>
                    </div>
                  ) : (
                    <div className="space-y-3">
                      {selectedFeatures
                        .sort((a, b) => a.order - b.order)
                        .map((feature, index) => (
                          <SelectedFeatureCard key={feature.id} feature={feature} index={index} />
                        ))}
                    </div>
                  )}
                </div>

                {/* Actions */}
                {selectedFeatures.length > 0 && (
                  <div className="space-y-2">
                    <Button className="w-full bg-blue-600 hover:bg-blue-700">
                      Continue to Business Context
                      <ArrowRight className="ml-2 h-4 w-4" />
                    </Button>
                    <Button variant="outline" className="w-full bg-transparent" onClick={() => setSelectedFeatures([])}>
                      Clear All Features
                    </Button>
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    </div>
  )
}
