import React, { useState } from "react";
import { motion } from "framer-motion";
import { Navigation } from "../components/Navigation";
import { Footer } from "../components/Footer";
import { Card, CardContent } from "../components/ui/card";
import { Button } from "../components/ui/button";
import { Badge } from "../components/ui/badge";
import { Input } from "../components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../components/ui/select";
import { 
  Search, Filter, ArrowRight, ExternalLink, Clock, Users, TrendingUp, 
  Star, Award, Building2, Smartphone, Heart, ShoppingCart, GraduationCap,
  FileText, ArrowUpRight
} from "lucide-react";
import { ImageWithFallback } from "../components/figma/ImageWithFallback";
import { navigateTo } from "../App";

// High-quality project images
const ranOutOfImage = "https://images.unsplash.com/photo-1551650975-87deedd944c3?w=600&h=400&fit=crop&auto=format";
const seezunImage = "https://images.unsplash.com/photo-1512941937669-90a1b58e7e9c?w=600&h=400&fit=crop&auto=format";
const wokaImage = "https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?w=600&h=400&fit=crop&auto=format";
const regroupImage = "https://images.unsplash.com/photo-1517077304055-6e89abbf09b0?w=600&h=400&fit=crop&auto=format";
const tanamiImage = "https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=600&h=400&fit=crop&auto=format";
const tradersCircuitImage = "https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=600&h=400&fit=crop&auto=format";
const goodTimesImage = "https://images.unsplash.com/photo-1557804506-669a67965ba0?w=600&h=400&fit=crop&auto=format";
const prospertyImage = "https://images.unsplash.com/photo-1554224155-8d04cb21cd6c?w=600&h=400&fit=crop&auto=format";

const caseStudies = [
  {
    id: 1,
    title: "RanOutOf",
    subtitle: "Household Management Revolution",
    description: "Smart inventory management app that helps households track supplies, create shopping lists, and reduce waste through intelligent notifications.",
    image: ranOutOfImage,
    category: "Lifestyle",
    industry: "Consumer",
    client: "RanOutOf Technologies",
    duration: "6 months",
    teamSize: "8 developers",
    technologies: ["React Native", "Node.js", "MongoDB", "AI/ML", "Push Notifications"],
    results: [
      { metric: "Food Waste Reduction", value: "-45%" },
      { metric: "Shopping Efficiency", value: "+60%" },
      { metric: "User Satisfaction", value: "4.7/5" }
    ],
    awards: ["Best Lifestyle App 2023"],
    featured: true,
    link: "/projects/ranoutof",
    icon: Heart
  },
  {
    id: 2,
    title: "Seezun",
    subtitle: "E-commerce Platform Innovation",
    description: "Next-generation e-commerce solution with AI-powered recommendations, seamless checkout, and advanced analytics for modern retailers.",
    image: seezunImage,
    category: "E-commerce",
    industry: "Retail",
    client: "Seezun Retail Corp",
    duration: "8 months",
    teamSize: "12 developers",
    technologies: ["React", "Python", "PostgreSQL", "Redis", "Stripe", "AWS"],
    results: [
      { metric: "Conversion Rate", value: "+185%" },
      { metric: "Page Load Speed", value: "1.8s" },
      { metric: "Revenue Growth", value: "+240%" }
    ],
    awards: ["E-commerce Excellence Award", "Innovation in Retail"],
    featured: true,
    link: "/projects/seezun",
    icon: ShoppingCart
  },
  {
    id: 3,
    title: "Woka",
    subtitle: "Fitness & Wellness Platform",
    description: "Comprehensive fitness app with personalized workout plans, nutrition tracking, and community features that won multiple industry awards.",
    image: wokaImage,
    category: "Health & Fitness",
    industry: "Healthcare",
    client: "Woka Wellness Inc",
    duration: "10 months",
    teamSize: "15 developers",
    technologies: ["Flutter", "Firebase", "TensorFlow", "HealthKit", "Google Fit"],
    results: [
      { metric: "User Retention", value: "+320%" },
      { metric: "Workout Completions", value: "2M+" },
      { metric: "App Store Rating", value: "4.9/5" }
    ],
    awards: ["App of the Year 2023", "Health Innovation Award"],
    featured: true,
    link: "/projects/woka",
    icon: Heart
  },
  {
    id: 4,
    title: "Regroup",
    subtitle: "Social Networking Platform",
    description: "Revolutionary social platform connecting communities worldwide with advanced messaging, group management, and content sharing capabilities.",
    image: regroupImage,
    category: "Social",
    industry: "Technology",
    client: "Regroup Technologies",
    duration: "12 months",
    teamSize: "18 developers",
    technologies: ["React Native", "Node.js", "MongoDB", "WebRTC", "Socket.io"],
    results: [
      { metric: "User Engagement", value: "+280%" },
      { metric: "Active Communities", value: "75K+" },
      { metric: "Daily Messages", value: "5M+" }
    ],
    awards: ["Best Social App 2023"],
    featured: true,
    link: "/projects/regroup",
    icon: Users
  },
  {
    id: 5,
    title: "Tanami",
    subtitle: "Agricultural Technology Solution",
    description: "Smart farming platform that combines IoT sensors, weather data, and machine learning to optimize crop yields and reduce resource usage.",
    image: tanamiImage,
    category: "AgriTech",
    industry: "Agriculture",
    client: "Tanami Farms Ltd",
    duration: "9 months",
    teamSize: "10 developers",
    technologies: ["React", "Python", "IoT", "TensorFlow", "AWS IoT"],
    results: [
      { metric: "Crop Yield Increase", value: "+35%" },
      { metric: "Water Usage Reduction", value: "-40%" },
      { metric: "Cost Savings", value: "$2.5M" }
    ],
    awards: ["AgriTech Innovation Award"],
    featured: false,
    link: "/projects/tanami",
    icon: Building2
  },
  {
    id: 6,
    title: "Traders Circuit",
    subtitle: "Financial Trading Platform",
    description: "Advanced trading platform with real-time market data, algorithmic trading capabilities, and comprehensive portfolio management tools.",
    image: tradersCircuitImage,
    category: "FinTech",
    industry: "Finance",
    client: "Traders Circuit LLC",
    duration: "14 months",
    teamSize: "20 developers",
    technologies: ["React", "Node.js", "WebSocket", "Redis", "PostgreSQL"],
    results: [
      { metric: "Trading Volume", value: "$500M+" },
      { metric: "Platform Uptime", value: "99.9%" },
      { metric: "User Growth", value: "+150%" }
    ],
    awards: ["FinTech Excellence Award"],
    featured: false,
    link: "/projects/traderscircuit",
    icon: TrendingUp
  },
  {
    id: 7,
    title: "Good Times",
    subtitle: "Event Management Platform",
    description: "Comprehensive event management solution for organizing, promoting, and managing events of all sizes with integrated ticketing and analytics.",
    image: goodTimesImage,
    category: "Events",
    industry: "Entertainment",
    client: "Good Times Events",
    duration: "7 months",
    teamSize: "9 developers",
    technologies: ["Vue.js", "Laravel", "MySQL", "Stripe", "SendGrid"],
    results: [
      { metric: "Events Managed", value: "10K+" },
      { metric: "Ticket Sales", value: "+200%" },
      { metric: "Customer Satisfaction", value: "4.8/5" }
    ],
    awards: ["Event Tech Innovation"],
    featured: false,
    link: "/projects/goodtimes",
    icon: Star
  },
  {
    id: 8,
    title: "Prosperty",
    subtitle: "Real Estate Investment Platform",
    description: "Digital platform for real estate investment with property analysis, portfolio management, and automated investment recommendations.",
    image: prospertyImage,
    category: "PropTech",
    industry: "Real Estate",
    client: "Prosperty Investments",
    duration: "11 months",
    teamSize: "13 developers",
    technologies: ["React", "Python", "PostgreSQL", "ML", "Blockchain"],
    results: [
      { metric: "Investment Volume", value: "$100M+" },
      { metric: "Portfolio Performance", value: "+25%" },
      { metric: "User Base Growth", value: "+300%" }
    ],
    awards: ["PropTech Innovation Award"],
    featured: false,
    link: "/projects/prosperty",
    icon: Building2
  }
];

const industries = ["All Industries", "Consumer", "Retail", "Healthcare", "Technology", "Agriculture", "Finance", "Entertainment", "Real Estate"];
const categories = ["All Categories", "Lifestyle", "E-commerce", "Health & Fitness", "Social", "AgriTech", "FinTech", "Events", "PropTech"];

export const CaseStudies = () => {
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedIndustry, setSelectedIndustry] = useState("All Industries");
  const [selectedCategory, setSelectedCategory] = useState("All Categories");
  const [showFeaturedOnly, setShowFeaturedOnly] = useState(false);

  // Filter case studies based on search and filters
  const filteredCaseStudies = caseStudies.filter(study => {
    const matchesSearch = study.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         study.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         study.technologies.some(tech => tech.toLowerCase().includes(searchTerm.toLowerCase()));
    
    const matchesIndustry = selectedIndustry === "All Industries" || study.industry === selectedIndustry;
    const matchesCategory = selectedCategory === "All Categories" || study.category === selectedCategory;
    const matchesFeatured = !showFeaturedOnly || study.featured;

    return matchesSearch && matchesIndustry && matchesCategory && matchesFeatured;
  });

  return (
    <div className="dark min-h-screen bg-background">
      <Navigation />
      
      {/* Hero Section */}
      <section className="relative pt-24 pb-20 overflow-hidden bg-black">
        <div className="absolute inset-0 bg-gradient-to-br from-accent/5 via-background to-background" />
        
        <motion.div 
          initial={{ opacity: 0, y: 30 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8 }}
          className="relative container mx-auto px-6 lg:px-8"
        >
          <div className="max-w-4xl mx-auto text-center">
            <Badge variant="outline" className="mb-6 border-accent/20 text-accent">
              Our Success Stories
            </Badge>
            <h1 className="text-4xl md:text-6xl lg:text-7xl font-semibold leading-tight mb-6">
              <span className="text-white">Case Studies That </span>
              <span className="text-accent">Define Excellence</span>
            </h1>
            <p className="text-xl text-gray-300 leading-relaxed max-w-3xl mx-auto">
              Explore our portfolio of award-winning projects that have transformed businesses and delighted millions of users across diverse industries.
            </p>
          </div>
        </motion.div>
      </section>

      {/* Filters Section */}
      <section className="py-12 bg-background border-b border-white/10">
        <div className="container mx-auto px-6 lg:px-8">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.2 }}
            className="max-w-6xl mx-auto"
          >
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 items-end">
              {/* Search */}
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4" />
                <Input
                  placeholder="Search case studies..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10 bg-card/50 border-white/10"
                />
              </div>

              {/* Industry Filter */}
              <Select value={selectedIndustry} onValueChange={setSelectedIndustry}>
                <SelectTrigger className="bg-card/50 border-white/10">
                  <SelectValue placeholder="Select Industry" />
                </SelectTrigger>
                <SelectContent>
                  {industries.map((industry) => (
                    <SelectItem key={industry} value={industry}>
                      {industry}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>

              {/* Category Filter */}
              <Select value={selectedCategory} onValueChange={setSelectedCategory}>
                <SelectTrigger className="bg-card/50 border-white/10">
                  <SelectValue placeholder="Select Category" />
                </SelectTrigger>
                <SelectContent>
                  {categories.map((category) => (
                    <SelectItem key={category} value={category}>
                      {category}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>

              {/* Featured Toggle */}
              <Button
                variant={showFeaturedOnly ? "default" : "outline"}
                onClick={() => setShowFeaturedOnly(!showFeaturedOnly)}
                className="justify-center"
              >
                <Award className="w-4 h-4 mr-2" />
                Featured Only
              </Button>
            </div>

            {/* Results Count */}
            <div className="mt-6 text-center">
              <p className="text-muted-foreground">
                Showing {filteredCaseStudies.length} of {caseStudies.length} case studies
              </p>
            </div>
          </motion.div>
        </div>
      </section>

      {/* Case Studies Grid */}
      <section className="py-20 bg-background">
        <div className="container mx-auto px-6 lg:px-8">
          <div className="max-w-7xl mx-auto">
            <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
              {filteredCaseStudies.map((study, index) => {
                const IconComponent = study.icon;
                return (
                  <motion.div
                    key={study.id}
                    initial={{ opacity: 0, y: 40 }}
                    whileInView={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.6, delay: index * 0.1 }}
                    viewport={{ once: true }}
                    whileHover={{ y: -8, scale: 1.02 }}
                    className="group cursor-pointer"
                    onClick={() => navigateTo(study.link)}
                  >
                    <Card className="bg-card/50 backdrop-blur-md border-white/10 hover:border-accent/30 transition-all duration-500 shadow-lg hover:shadow-2xl hover:shadow-accent/10 rounded-2xl overflow-hidden h-full">
                      <CardContent className="p-0 flex flex-col h-full">
                        {/* Image Header */}
                        <div className="relative overflow-hidden">
                          <ImageWithFallback
                            src={study.image}
                            alt={study.title}
                            className="w-full h-48 object-cover transition-transform duration-500 group-hover:scale-110"
                          />
                          <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent" />
                          
                          {/* Category Badge */}
                          <div className="absolute top-4 left-4">
                            <Badge className="bg-accent/90 text-white border-0">
                              {study.category}
                            </Badge>
                          </div>

                          {/* Featured Badge */}
                          {study.featured && (
                            <div className="absolute top-4 right-4">
                              <div className="bg-amber-500/90 text-white px-3 py-1 rounded-full text-xs font-medium flex items-center gap-1">
                                <Star className="w-3 h-3 fill-current" />
                                Featured
                              </div>
                            </div>
                          )}

                          {/* Icon Overlay */}
                          <div className="absolute bottom-4 left-4">
                            <div className="w-12 h-12 bg-white/20 backdrop-blur-md rounded-full flex items-center justify-center">
                              <IconComponent className="w-6 h-6 text-white" />
                            </div>
                          </div>
                        </div>

                        {/* Content */}
                        <div className="p-6 flex-1 flex flex-col">
                          <div className="mb-4">
                            <h3 className="text-xl font-bold text-foreground mb-2 group-hover:text-accent transition-colors">
                              {study.title}
                            </h3>
                            <p className="text-accent font-medium text-sm mb-2">
                              {study.subtitle}
                            </p>
                            <p className="text-muted-foreground text-sm leading-relaxed">
                              {study.description}
                            </p>
                          </div>

                          {/* Key Results */}
                          <div className="grid grid-cols-2 gap-3 mb-4 p-3 bg-accent/5 rounded-lg border border-accent/10">
                            {study.results.slice(0, 2).map((result, idx) => (
                              <div key={idx} className="text-center">
                                <div className="text-sm font-bold text-accent">
                                  {result.value}
                                </div>
                                <div className="text-xs text-muted-foreground">
                                  {result.metric}
                                </div>
                              </div>
                            ))}
                          </div>

                          {/* Technologies */}
                          <div className="mb-4">
                            <div className="flex flex-wrap gap-1">
                              {study.technologies.slice(0, 3).map((tech) => (
                                <Badge key={tech} variant="secondary" className="text-xs bg-muted/30">
                                  {tech}
                                </Badge>
                              ))}
                              {study.technologies.length > 3 && (
                                <Badge variant="secondary" className="text-xs bg-muted/30">
                                  +{study.technologies.length - 3}
                                </Badge>
                              )}
                            </div>
                          </div>

                          {/* Project Info */}
                          <div className="grid grid-cols-2 gap-2 mb-4 text-xs text-muted-foreground">
                            <div className="flex items-center gap-1">
                              <Clock className="w-3 h-3" />
                              {study.duration}
                            </div>
                            <div className="flex items-center gap-1">
                              <Users className="w-3 h-3" />
                              {study.teamSize}
                            </div>
                          </div>

                          {/* Awards */}
                          {study.awards.length > 0 && (
                            <div className="mb-4">
                              <div className="flex items-center gap-1 text-xs text-amber-600">
                                <Award className="w-3 h-3" />
                                <span className="truncate">{study.awards[0]}</span>
                              </div>
                            </div>
                          )}

                          {/* CTA Button */}
                          <Button 
                            variant="ghost" 
                            className="w-full justify-between text-accent hover:text-accent hover:bg-accent/10 group-hover:translate-x-1 transition-all duration-300 mt-auto"
                            onClick={(e) => {
                              e.stopPropagation();
                              navigateTo(study.link);
                            }}
                          >
                            <span className="text-sm">View Case Study</span>
                            <ArrowRight className="w-4 h-4" />
                          </Button>
                        </div>
                      </CardContent>
                    </Card>
                  </motion.div>
                );
              })}
            </div>
          </div>
        </div>
      </section>

      {/* CTA Section */}
      <section className="py-20 bg-black">
        <div className="container mx-auto px-6 lg:px-8">
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            whileInView={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8 }}
            viewport={{ once: true }}
            className="text-center max-w-4xl mx-auto"
          >
            <h2 className="text-3xl lg:text-4xl font-semibold text-white mb-6">
              Ready to Create Your Own Success Story?
            </h2>
            <p className="text-xl text-gray-300 leading-relaxed mb-8">
              Join the ranks of industry leaders who have transformed their businesses with our innovative solutions.
            </p>
            <div className="flex flex-col sm:flex-row gap-4 justify-center">
              <Button 
                size="lg"
                className="bg-accent hover:bg-accent/90 text-white"
                onClick={() => navigateTo("/start-a-project")}
              >
                Start Your Project
                <ArrowUpRight className="w-4 h-4 ml-2" />
              </Button>
              <Button 
                size="lg"
                variant="outline"
                onClick={() => navigateTo("/contact-us")}
              >
                Schedule Consultation
                <ArrowRight className="w-4 h-4 ml-2" />
              </Button>
            </div>
          </motion.div>
        </div>
      </section>

      <Footer />
    </div>
  );
};