'use client';

import { useState } from 'react';
import Link from 'next/link';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { FilterSelect } from '@/components/ui/filter-select';
import { WBSProgressWidget } from '@/components/project/wbs-progress-widget';
import { mockProjects, mockUsers } from '@/lib/mock-data';
import { PROJECT_TYPES, PROJECT_STATUS, PROJECT_PRIORITY } from '@/lib/constants';
import { Project, ProjectType, ProjectStatus, ProjectPriority } from '@/lib/types';
import { formatDate as formatDateUtil } from '@/lib/date-utils';
import { 
  FolderOpen, 
  Plus, 
  Search, 
  Filter,
  MoreHorizontal,
  Calendar,
  DollarSign,
  Users,
  Clock,
  Eye
} from 'lucide-react';
import { 
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger
} from '@/components/ui/dropdown-menu';

const getStatusBadgeColor = (status: ProjectStatus) => {
  const colors = {
    planning: 'bg-primary/15 text-primary border-primary/20',
    in_progress: 'bg-yellow-100 text-yellow-800 border-yellow-200',
    testing: 'bg-primary/10 text-primary border-primary/20',
    completed: 'bg-green-100 text-green-800 border-green-200',
    on_hold: 'bg-orange-100 text-orange-800 border-orange-200',
    cancelled: 'bg-red-100 text-red-800 border-red-200'
  };
  return colors[status];
};

const getPriorityBadgeColor = (priority: ProjectPriority) => {
  const colors = {
    low: 'bg-muted text-foreground border-border',
    medium: 'bg-primary/15 text-primary border-primary/20',
    high: 'bg-orange-100 text-orange-800 border-orange-200',
    critical: 'bg-red-100 text-red-800 border-red-200'
  };
  return colors[priority];
};

export default function ProjectsPage() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedType, setSelectedType] = useState<string>('all');
  const [selectedStatus, setSelectedStatus] = useState<string>('all');

  const filteredProjects = mockProjects.filter(project => {
    const matchesSearch = project.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         project.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         project.team.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesType = selectedType === 'all' || project.type === selectedType;
    const matchesStatus = selectedStatus === 'all' || project.status === selectedStatus;
    return matchesSearch && matchesType && matchesStatus;
  });

  const getUserName = (userId: string) => {
    const user = mockUsers.find(u => u.id === userId);
    return user ? user.name : 'Unknown User';
  };

  const getInitials = (name: string) => {
    return name.split(' ').map(n => n[0]).join('').toUpperCase();
  };

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
    }).format(amount);
  };

  const formatDate = (date: Date) => {
    return formatDateUtil(date, { format: 'medium' });
  };

  return (
    <div className="space-y-8">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-3">
          <div className="p-2 bg-primary/10 rounded-lg">
            <FolderOpen className="h-6 w-6 text-primary" />
          </div>
          <div>
            <h2 className="text-2xl font-semibold tracking-tight text-foreground">All projects</h2>
            <p className="text-muted-foreground">Manage and track all your projects</p>
          </div>
        </div>
        <Link href="/dashboard/projects/create">
          <Button className="bg-primary hover:bg-primary">
            <Plus className="h-4 w-4 mr-2" />
            New Project
          </Button>
        </Link>
      </div>

      {/* Filters */}
      <Card className="p-6">
        <div className="flex flex-col lg:flex-row gap-4">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
            <Input
              placeholder="Search projects by name, description, or team..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10"
            />
          </div>
          <div className="flex items-center space-x-4">
            <div className="flex items-center space-x-2">
              <Filter className="h-4 w-4 text-muted-foreground" />
              <FilterSelect
                value={selectedType}
                onValueChange={setSelectedType}
                placeholder="All Types"
                options={[
                  { value: 'all', label: 'All Types' },
                  { value: 'web_app', label: 'Web Application' },
                  { value: 'mobile_app', label: 'Mobile Application' },
                  { value: 'desktop_app', label: 'Desktop Application' },
                  { value: 'api', label: 'API/Backend' },
                  { value: 'website', label: 'Website' },
                  { value: 'other', label: 'Other' },
                ]}
              />
            </div>
            <FilterSelect
              value={selectedStatus}
              onValueChange={setSelectedStatus}
              placeholder="All Status"
              options={[
                { value: 'all', label: 'All Status' },
                { value: 'planning', label: 'Planning' },
                { value: 'in_progress', label: 'In Progress' },
                { value: 'testing', label: 'Testing' },
                { value: 'completed', label: 'Completed' },
                { value: 'on_hold', label: 'On Hold' },
                { value: 'cancelled', label: 'Cancelled' },
              ]}
            />
          </div>
        </div>
      </Card>

      {/* Projects Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
        {filteredProjects.map((project) => (
          <Card key={project.id} className="p-4 hover:shadow-lg transition-all duration-200">
            <div className="flex items-start justify-between mb-4">
              <div className="flex-1 min-w-0">
                <h3 className="font-semibold text-foreground text-lg mb-2 truncate">{project.name}</h3>
                <p className="text-sm text-muted-foreground line-clamp-2 mb-3">{project.description}</p>
              </div>
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" size="sm" className="h-8 w-8 p-0 ml-2 flex-shrink-0">
                    <MoreHorizontal className="h-4 w-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuItem>Edit Project</DropdownMenuItem>
                  <DropdownMenuItem>Assign Users</DropdownMenuItem>
                  <DropdownMenuItem className="text-red-600">Delete Project</DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>

            {/* Enhanced WBS Progress Widget */}
            <div className="mb-4">
              <WBSProgressWidget projectId={project.id} variant="card" />
            </div>

            <div className="space-y-3 mb-4">
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">Type</span>
                <Badge variant="outline" className="bg-primary/10 text-primary border-primary/20">
                  {PROJECT_TYPES[project.type]}
                </Badge>
              </div>
              
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">Status</span>
                <Badge variant="outline" className={getStatusBadgeColor(project.status)}>
                  {PROJECT_STATUS[project.status]}
                </Badge>
              </div>
              
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">Priority</span>
                <Badge variant="outline" className={getPriorityBadgeColor(project.priority)}>
                  {PROJECT_PRIORITY[project.priority]}
                </Badge>
              </div>
            </div>

            <div className="space-y-2 text-sm text-muted-foreground mb-4">
              <div className="flex items-center space-x-2">
                <Calendar className="h-4 w-4" />
                <span>Start: {formatDate(project.startDate)}</span>
              </div>
              {project.endDate && (
                <div className="flex items-center space-x-2">
                  <Clock className="h-4 w-4" />
                  <span>End: {formatDate(project.endDate)}</span>
                </div>
              )}
              {project.budget && (
                <div className="flex items-center space-x-2">
                  <DollarSign className="h-4 w-4" />
                  <span>Budget: {formatCurrency(project.budget)}</span>
                </div>
              )}
            </div>

            <div className="pt-4 border-t border-border">
              <div className="flex items-center justify-between mb-3">
                <div className="flex items-center space-x-2">
                  <Users className="h-4 w-4 text-muted-foreground" />
                  <span className="text-sm text-muted-foreground">{project.team}</span>
                </div>
                <div className="flex -space-x-2">
                  {project.assignedUsers.slice(0, 3).map((userId) => (
                    <Avatar key={userId} className="h-8 w-8 border-2 border-white">
                      <AvatarFallback className="bg-primary/15 text-primary text-xs font-semibold">
                        {getInitials(getUserName(userId))}
                      </AvatarFallback>
                    </Avatar>
                  ))}
                  {project.assignedUsers.length > 3 && (
                    <div className="h-8 w-8 rounded-full bg-muted border-2 border-white flex items-center justify-center">
                      <span className="text-xs font-medium text-muted-foreground">
                        +{project.assignedUsers.length - 3}
                      </span>
                    </div>
                  )}
                </div>
              </div>
              
              {/* View Details Button */}
              <Link href={`/dashboard/projects/${project.id}`} className="block">
                <Button className="w-full bg-primary hover:bg-primary">
                  <Eye className="h-4 w-4 mr-2" />
                  View Details
                </Button>
              </Link>
            </div>
          </Card>
        ))}
      </div>

      {filteredProjects.length === 0 && (
        <Card className="p-12 text-center">
          <FolderOpen className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
          <h3 className="text-lg font-semibold text-foreground mb-2">No projects found</h3>
          <p className="text-muted-foreground mb-4">Try adjusting your search or filter criteria.</p>
          <Link href="/dashboard/projects/create">
            <Button>
              <Plus className="h-4 w-4 mr-2" />
              Create Your First Project
            </Button>
          </Link>
        </Card>
      )}
    </div>
  );
}