import React, { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { 
  Play, Search, Calendar, Users, FileText, UserPlus, Building2, 
  DollarSign, MessageSquare, Award, TrendingUp, MapPin, 
  Briefcase, Package, CheckSquare, Headphones, Mail
} from "lucide-react";
import PageHeader from "../components/common/PageHeader";

export default function Tutorials() {
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [playingVideo, setPlayingVideo] = useState(null);

  const tutorials = [
    {
      id: 1,
      title: "How to Create an Event Order",
      description: "Learn how to create a new event booking with staff requirements, shifts, and scheduling",
      category: "Events",
      duration: "3:45",
      icon: Calendar,
      videoUrl: "https://www.youtube.com/embed/dQw4w9WgXcQ",
      steps: [
        "Navigate to Events page",
        "Click 'Create Event' button",
        "Fill in event details (name, date, location)",
        "Add shift requirements and roles",
        "Set headcount for each position",
        "Review and submit"
      ]
    },
    {
      id: 2,
      title: "Inviting Team Members",
      description: "Step-by-step guide to invite new members to your team and assign them to hubs",
      category: "Team Management",
      duration: "2:30",
      icon: UserPlus,
      videoUrl: "https://www.youtube.com/embed/dQw4w9WgXcQ",
      steps: [
        "Go to Teams page",
        "Click 'Invite Member' button",
        "Enter member's name and email",
        "Select role and department",
        "Choose hub location",
        "Send invitation email"
      ]
    },
    {
      id: 3,
      title: "Creating and Managing Hubs",
      description: "How to create location hubs and organize departments within them",
      category: "Team Management",
      duration: "4:15",
      icon: MapPin,
      videoUrl: "https://www.youtube.com/embed/dQw4w9WgXcQ",
      steps: [
        "Navigate to Teams → Hubs tab",
        "Click 'Create Hub' button",
        "Enter hub name (e.g., BVG300)",
        "Add location address",
        "Assign hub manager",
        "Add departments with cost centers"
      ]
    },
    {
      id: 4,
      title: "Staff Assignment & Scheduling",
      description: "Assign staff to events, manage schedules, and handle conflicts",
      category: "Staff Management",
      duration: "5:20",
      icon: Users,
      videoUrl: "https://www.youtube.com/embed/dQw4w9WgXcQ",
      steps: [
        "Open event details",
        "Click 'Assign Staff' button",
        "Filter staff by role and rating",
        "Select staff members",
        "Review conflict warnings",
        "Confirm assignments"
      ]
    },
    {
      id: 5,
      title: "Creating and Sending Invoices",
      description: "Generate invoices from events and send them to clients",
      category: "Invoicing",
      duration: "3:50",
      icon: FileText,
      videoUrl: "https://www.youtube.com/embed/dQw4w9WgXcQ",
      steps: [
        "Go to Invoices page",
        "Click 'Create Invoice'",
        "Select event or create manually",
        "Review line items and totals",
        "Set payment terms",
        "Send to client via email"
      ]
    },
    {
      id: 6,
      title: "Vendor Onboarding Process",
      description: "Complete guide to onboarding new vendors with compliance documents",
      category: "Vendor Management",
      duration: "6:10",
      icon: Package,
      videoUrl: "https://www.youtube.com/embed/dQw4w9WgXcQ",
      steps: [
        "Navigate to Vendors",
        "Click 'Add Vendor'",
        "Enter vendor details and contacts",
        "Upload W9 and COI documents",
        "Set coverage regions and roles",
        "Submit for approval"
      ]
    },
    {
      id: 7,
      title: "Managing Vendor Rates",
      description: "Set up and manage vendor pricing, markups, and client rates",
      category: "Vendor Management",
      duration: "4:30",
      icon: DollarSign,
      videoUrl: "https://www.youtube.com/embed/dQw4w9WgXcQ",
      steps: [
        "Go to Vendor Rates page",
        "Click 'Add New Rate'",
        "Select category and role",
        "Enter employee wage",
        "Set markup and vendor fee %",
        "Review client rate and save"
      ]
    },
    {
      id: 8,
      title: "Staff Onboarding Tutorial",
      description: "Onboard new staff members with all required information and documents",
      category: "Staff Management",
      duration: "5:00",
      icon: Users,
      videoUrl: "https://www.youtube.com/embed/dQw4w9WgXcQ",
      steps: [
        "Navigate to Onboarding page",
        "Enter staff personal details",
        "Add employment information",
        "Upload certifications",
        "Set availability and skills",
        "Complete profile setup"
      ]
    },
    {
      id: 9,
      title: "Using the Messaging System",
      description: "Communicate with team members, vendors, and clients through built-in messaging",
      category: "Communication",
      duration: "2:45",
      icon: MessageSquare,
      videoUrl: "https://www.youtube.com/embed/dQw4w9WgXcQ",
      steps: [
        "Go to Messages page",
        "Start new conversation",
        "Select participants",
        "Type and send messages",
        "Attach files if needed",
        "Archive old conversations"
      ]
    },
    {
      id: 10,
      title: "Managing Certifications",
      description: "Track and manage employee certifications and compliance documents",
      category: "Compliance",
      duration: "3:20",
      icon: Award,
      videoUrl: "https://www.youtube.com/embed/dQw4w9WgXcQ",
      steps: [
        "Navigate to Certifications",
        "Click 'Add Certification'",
        "Select employee and cert type",
        "Enter issue and expiry dates",
        "Upload certificate document",
        "Submit for validation"
      ]
    },
    {
      id: 11,
      title: "Enterprise & Sector Setup",
      description: "Set up enterprise organizations and manage multiple sectors",
      category: "Enterprise",
      duration: "5:40",
      icon: Building2,
      videoUrl: "https://www.youtube.com/embed/dQw4w9WgXcQ",
      steps: [
        "Go to Enterprise Management",
        "Click 'Add Enterprise'",
        "Enter enterprise details",
        "Add brand family members",
        "Create sectors under enterprise",
        "Link partners to sectors"
      ]
    },
    {
      id: 12,
      title: "Partner & Client Management",
      description: "Add partners, manage sites, and configure client relationships",
      category: "Partners",
      duration: "4:00",
      icon: Briefcase,
      videoUrl: "https://www.youtube.com/embed/dQw4w9WgXcQ",
      steps: [
        "Navigate to Partners",
        "Click 'Add Partner'",
        "Enter partner information",
        "Add multiple sites",
        "Configure allowed vendors",
        "Set payment terms"
      ]
    },
    {
      id: 13,
      title: "Generating Reports & Analytics",
      description: "Create custom reports and analyze workforce performance data",
      category: "Reports",
      duration: "4:25",
      icon: TrendingUp,
      videoUrl: "https://www.youtube.com/embed/dQw4w9WgXcQ",
      steps: [
        "Go to Reports page",
        "Select report type",
        "Choose date range",
        "Apply filters (vendor, client, etc.)",
        "Generate report",
        "Export to PDF or Excel"
      ]
    },
    {
      id: 14,
      title: "Task Board & Project Management",
      description: "Use the task board to track work items and collaborate with your team",
      category: "Productivity",
      duration: "3:10",
      icon: CheckSquare,
      videoUrl: "https://www.youtube.com/embed/dQw4w9WgXcQ",
      steps: [
        "Navigate to Task Board",
        "Create new task",
        "Assign to team members",
        "Set due dates and priority",
        "Move tasks between columns",
        "Mark tasks as complete"
      ]
    },
    {
      id: 15,
      title: "Role-Based Permissions",
      description: "Configure user roles and permissions across the platform",
      category: "Administration",
      duration: "3:55",
      icon: Users,
      videoUrl: "https://www.youtube.com/embed/dQw4w9WgXcQ",
      steps: [
        "Go to Permissions page",
        "Select user role",
        "Configure access levels",
        "Set entity permissions",
        "Enable/disable features",
        "Save permission settings"
      ]
    }
  ];

  const categories = ["all", ...new Set(tutorials.map(t => t.category))];

  const filteredTutorials = tutorials.filter(tutorial => {
    const matchesSearch = !searchTerm || 
      tutorial.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
      tutorial.description.toLowerCase().includes(searchTerm.toLowerCase());
    
    const matchesCategory = selectedCategory === "all" || tutorial.category === selectedCategory;
    
    return matchesSearch && matchesCategory;
  });

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 p-4 md:p-8">
      <div className="max-w-7xl mx-auto">
        <PageHeader
          title="📚 Tutorial Library"
          subtitle="Learn how to use KROW Workforce with step-by-step video guides"
        />

        {/* Search and Filters */}
        <div className="mb-8 flex flex-col md:flex-row gap-4">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-slate-400" />
            <Input
              placeholder="Search tutorials..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10 h-12 border-slate-300 focus:border-[#0A39DF]"
            />
          </div>
          
          <div className="flex gap-2 flex-wrap">
            {categories.map(category => (
              <Button
                key={category}
                variant={selectedCategory === category ? "default" : "outline"}
                onClick={() => setSelectedCategory(category)}
                className={selectedCategory === category ? "bg-[#0A39DF]" : ""}
              >
                {category === "all" ? "All Tutorials" : category}
              </Button>
            ))}
          </div>
        </div>

        {/* Tutorials Grid */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-12">
          {filteredTutorials.map((tutorial) => (
            <Card key={tutorial.id} className="border-2 border-slate-200 hover:border-[#0A39DF] hover:shadow-2xl transition-all duration-300 overflow-hidden group">
              <CardHeader className="bg-gradient-to-r from-slate-50 to-blue-50 border-b border-slate-100">
                <div className="flex items-start justify-between">
                  <div className="flex items-start gap-4">
                    <div className="w-12 h-12 bg-gradient-to-br from-[#0A39DF] to-[#1C323E] rounded-xl flex items-center justify-center text-white shadow-lg">
                      <tutorial.icon className="w-6 h-6" />
                    </div>
                    <div className="flex-1">
                      <CardTitle className="text-lg text-[#1C323E] group-hover:text-[#0A39DF] transition-colors">
                        {tutorial.title}
                      </CardTitle>
                      <p className="text-sm text-slate-600 mt-1">{tutorial.description}</p>
                    </div>
                  </div>
                  <Badge className="bg-blue-100 text-blue-700 border-blue-200">
                    {tutorial.duration}
                  </Badge>
                </div>
              </CardHeader>
              
              <CardContent className="p-0">
                {/* Video Player */}
                {playingVideo === tutorial.id ? (
                  <div className="relative bg-black aspect-video">
                    <iframe
                      src={tutorial.videoUrl}
                      className="w-full h-full"
                      allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                      allowFullScreen
                    />
                  </div>
                ) : (
                  <div 
                    onClick={() => setPlayingVideo(tutorial.id)}
                    className="relative bg-gradient-to-br from-slate-200 to-slate-300 aspect-video flex items-center justify-center group-hover:from-blue-100 group-hover:to-indigo-200 transition-all cursor-pointer"
                  >
                    <div className="absolute inset-0 flex items-center justify-center">
                      <div className="w-20 h-20 bg-gradient-to-br from-[#0A39DF] to-[#1C323E] rounded-full flex items-center justify-center shadow-2xl group-hover:scale-110 transition-transform">
                        <Play className="w-10 h-10 text-white ml-1" />
                      </div>
                    </div>
                    <div className="absolute bottom-4 left-4 bg-black/70 backdrop-blur-sm text-white px-4 py-2 rounded-lg text-sm font-semibold">
                      Watch Tutorial
                    </div>
                  </div>
                )}

                {/* Steps */}
                <div className="p-6 bg-white">
                  <h4 className="font-bold text-slate-700 mb-3 text-sm uppercase tracking-wide">What You'll Learn:</h4>
                  <ul className="space-y-2">
                    {tutorial.steps.map((step, idx) => (
                      <li key={idx} className="flex items-start gap-3 text-sm text-slate-600">
                        <div className="w-6 h-6 bg-blue-100 text-blue-700 rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0 mt-0.5">
                          {idx + 1}
                        </div>
                        <span>{step}</span>
                      </li>
                    ))}
                  </ul>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>

        {/* No Results */}
        {filteredTutorials.length === 0 && (
          <div className="text-center py-16 bg-white rounded-xl border-2 border-dashed border-slate-200">
            <Search className="w-16 h-16 mx-auto text-slate-300 mb-4" />
            <h3 className="text-xl font-semibold text-slate-700 mb-2">No Tutorials Found</h3>
            <p className="text-slate-500">Try adjusting your search or filters</p>
          </div>
        )}

        {/* Support Section */}
        <Card className="border-2 border-blue-200 bg-gradient-to-br from-blue-50 to-indigo-50">
          <CardContent className="p-8 text-center">
            <div className="w-20 h-20 mx-auto mb-6 bg-gradient-to-br from-blue-100 to-indigo-100 rounded-full flex items-center justify-center">
              <Headphones className="w-10 h-10 text-blue-600" />
            </div>
            <h2 className="text-2xl font-bold text-[#1C323E] mb-3">
              Questions about KROW Workforce?
            </h2>
            <p className="text-slate-600 mb-6 text-lg">
              Contact KROW support team for personalized help
            </p>
            <div className="flex flex-col sm:flex-row items-center justify-center gap-4">
              <Button size="lg" className="bg-gradient-to-r from-[#0A39DF] to-[#1C323E] text-white shadow-lg">
                <MessageSquare className="w-5 h-5 mr-2" />
                Chat with Support
              </Button>
              <Button size="lg" variant="outline" className="border-2 border-blue-300 hover:bg-blue-50">
                <Mail className="w-5 h-5 mr-2" />
                Email: support@krow.com
              </Button>
            </div>
          </CardContent>
        </Card>

        {/* Quick Links */}
        <div className="mt-8 grid grid-cols-1 md:grid-cols-3 gap-6">
          <Card className="border-slate-200 hover:shadow-lg transition-all">
            <CardContent className="p-6 text-center">
              <div className="w-14 h-14 mx-auto mb-4 bg-green-100 rounded-full flex items-center justify-center">
                <FileText className="w-7 h-7 text-green-600" />
              </div>
              <h3 className="font-bold text-[#1C323E] mb-2">Documentation</h3>
              <p className="text-sm text-slate-600 mb-4">Read the complete API docs</p>
              <Button variant="outline" size="sm" className="w-full">
                View Docs
              </Button>
            </CardContent>
          </Card>

          <Card className="border-slate-200 hover:shadow-lg transition-all">
            <CardContent className="p-6 text-center">
              <div className="w-14 h-14 mx-auto mb-4 bg-purple-100 rounded-full flex items-center justify-center">
                <Users className="w-7 h-7 text-purple-600" />
              </div>
              <h3 className="font-bold text-[#1C323E] mb-2">Community Forum</h3>
              <p className="text-sm text-slate-600 mb-4">Connect with other users</p>
              <Button variant="outline" size="sm" className="w-full">
                Join Forum
              </Button>
            </CardContent>
          </Card>

          <Card className="border-slate-200 hover:shadow-lg transition-all">
            <CardContent className="p-6 text-center">
              <div className="w-14 h-14 mx-auto mb-4 bg-amber-100 rounded-full flex items-center justify-center">
                <Award className="w-7 h-7 text-amber-600" />
              </div>
              <h3 className="font-bold text-[#1C323E] mb-2">Best Practices</h3>
              <p className="text-sm text-slate-600 mb-4">Learn from experts</p>
              <Button variant="outline" size="sm" className="w-full">
                Read Guide
              </Button>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}