'use client';

import { useState } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { DatePicker } from '@/components/ui/date-picker';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { WBSItem } from '@/lib/types';
import { mockUsers } from '@/lib/mock-data';
import { 
  Plus, 
  Edit, 
  Trash2, 
  ChevronRight, 
  ChevronDown,
  User,
  Clock,
  Calendar,
  MoreHorizontal,
  CheckCircle2,
  Circle,
  AlertCircle,
  Pause
} from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';

interface WorkBreakdownStructureProps {
  projectId: string;
}

// Mock WBS data
const mockWBSItems: WBSItem[] = [
  {
    id: '1',
    code: '1.0',
    title: 'Project Planning',
    description: 'Initial project planning and setup phase',
    level: 0,
    assignedTo: '1',
    estimatedHours: 40,
    actualHours: 35,
    status: 'completed',
    startDate: new Date('2024-01-15'),
    endDate: new Date('2024-01-25'),
    children: [
      {
        id: '1.1',
        code: '1.1',
        title: 'Requirements Gathering',
        description: 'Collect and document project requirements',
        parentId: '1',
        level: 1,
        assignedTo: '2',
        estimatedHours: 20,
        actualHours: 18,
        status: 'completed',
        startDate: new Date('2024-01-15'),
        endDate: new Date('2024-01-20'),
        children: []
      },
      {
        id: '1.2',
        code: '1.2',
        title: 'Technical Architecture',
        description: 'Design system architecture and technology stack',
        parentId: '1',
        level: 1,
        assignedTo: '3',
        estimatedHours: 20,
        actualHours: 17,
        status: 'completed',
        startDate: new Date('2024-01-20'),
        endDate: new Date('2024-01-25'),
        children: []
      }
    ]
  },
  {
    id: '2',
    code: '2.0',
    title: 'Frontend Development',
    description: 'User interface and user experience development',
    level: 0,
    assignedTo: '4',
    estimatedHours: 120,
    actualHours: 85,
    status: 'in_progress',
    startDate: new Date('2024-01-26'),
    endDate: new Date('2024-03-15'),
    children: [
      {
        id: '2.1',
        code: '2.1',
        title: 'UI Components',
        description: 'Develop reusable UI components',
        parentId: '2',
        level: 1,
        assignedTo: '4',
        estimatedHours: 60,
        actualHours: 45,
        status: 'in_progress',
        startDate: new Date('2024-01-26'),
        endDate: new Date('2024-02-20'),
        children: []
      },
      {
        id: '2.2',
        code: '2.2',
        title: 'Page Layouts',
        description: 'Create main application page layouts',
        parentId: '2',
        level: 1,
        assignedTo: '4',
        estimatedHours: 40,
        status: 'not_started',
        startDate: new Date('2024-02-21'),
        endDate: new Date('2024-03-10'),
        children: []
      },
      {
        id: '2.3',
        code: '2.3',
        title: 'Responsive Design',
        description: 'Implement responsive design for mobile devices',
        parentId: '2',
        level: 1,
        assignedTo: '4',
        estimatedHours: 20,
        status: 'not_started',
        startDate: new Date('2024-03-11'),
        endDate: new Date('2024-03-15'),
        children: []
      }
    ]
  },
  {
    id: '3',
    code: '3.0',
    title: 'Backend Development',
    description: 'Server-side development and API creation',
    level: 0,
    assignedTo: '3',
    estimatedHours: 100,
    status: 'not_started',
    startDate: new Date('2024-02-01'),
    endDate: new Date('2024-03-20'),
    children: [
      {
        id: '3.1',
        code: '3.1',
        title: 'Database Design',
        description: 'Design and implement database schema',
        parentId: '3',
        level: 1,
        assignedTo: '3',
        estimatedHours: 30,
        status: 'not_started',
        children: []
      },
      {
        id: '3.2',
        code: '3.2',
        title: 'API Development',
        description: 'Develop RESTful APIs',
        parentId: '3',
        level: 1,
        assignedTo: '3',
        estimatedHours: 50,
        status: 'not_started',
        children: []
      },
      {
        id: '3.3',
        code: '3.3',
        title: 'Authentication System',
        description: 'Implement user authentication and authorization',
        parentId: '3',
        level: 1,
        assignedTo: '3',
        estimatedHours: 20,
        status: 'not_started',
        children: []
      }
    ]
  }
];

const getStatusIcon = (status: WBSItem['status']) => {
  const icons = {
    not_started: Circle,
    in_progress: AlertCircle,
    completed: CheckCircle2,
    blocked: Pause
  };
  return icons[status];
};

const getStatusColor = (status: WBSItem['status']) => {
  const colors = {
    not_started: 'text-muted-foreground',
    in_progress: 'text-primary',
    completed: 'text-green-500',
    blocked: 'text-red-500'
  };
  return colors[status];
};

export function WorkBreakdownStructure({ projectId }: WorkBreakdownStructureProps) {
  const [wbsItems, setWbsItems] = useState<WBSItem[]>(mockWBSItems);
  const [expandedItems, setExpandedItems] = useState<Set<string>>(new Set(['1', '2', '3']));
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [selectedParent, setSelectedParent] = useState<string | null>(null);
  const [createType, setCreateType] = useState<'main' | 'sub'>('main');
  const [newItem, setNewItem] = useState({
    title: '',
    description: '',
    assignedTo: '',
    estimatedHours: '',
    startDate: '',
    endDate: ''
  });

  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 toggleExpanded = (itemId: string) => {
    const newExpanded = new Set(expandedItems);
    if (newExpanded.has(itemId)) {
      newExpanded.delete(itemId);
    } else {
      newExpanded.add(itemId);
    }
    setExpandedItems(newExpanded);
  };

  const generateNextCode = (parentId?: string) => {
    if (!parentId) {
      const topLevelItems = wbsItems.filter(item => item.level === 0);
      return `${topLevelItems.length + 1}.0`;
    }
    
    const parent = findItemById(parentId, wbsItems);
    if (!parent) return '1.0';
    
    const siblingCount = parent.children.length;
    const parentCode = parent.code.split('.');
    return `${parentCode[0]}.${siblingCount + 1}`;
  };

  const findItemById = (id: string, items: WBSItem[]): WBSItem | null => {
    for (const item of items) {
      if (item.id === id) return item;
      const found = findItemById(id, item.children);
      if (found) return found;
    }
    return null;
  };

  const handleCreateItem = () => {
    const parentItem = selectedParent ? findItemById(selectedParent, wbsItems) : null;
    const level = parentItem ? parentItem.level + 1 : 0;
    
    const newWBSItem: WBSItem = {
      id: Date.now().toString(),
      code: generateNextCode(selectedParent || undefined),
      title: newItem.title,
      description: newItem.description,
      parentId: selectedParent || undefined,
      level,
      assignedTo: newItem.assignedTo || undefined,
      estimatedHours: newItem.estimatedHours ? parseInt(newItem.estimatedHours) : undefined,
      status: 'not_started',
      startDate: newItem.startDate ? new Date(newItem.startDate) : undefined,
      endDate: newItem.endDate ? new Date(newItem.endDate) : undefined,
      children: []
    };

    if (selectedParent) {
      // Add to parent's children
      const updateItems = (items: WBSItem[]): WBSItem[] => {
        return items.map(item => {
          if (item.id === selectedParent) {
            return { ...item, children: [...item.children, newWBSItem] };
          }
          return { ...item, children: updateItems(item.children) };
        });
      };
      setWbsItems(updateItems(wbsItems));
    } else {
      // Add as top-level item
      setWbsItems([...wbsItems, newWBSItem]);
    }

    setNewItem({
      title: '',
      description: '',
      assignedTo: '',
      estimatedHours: '',
      startDate: '',
      endDate: ''
    });
    setSelectedParent(null);
    setIsCreateDialogOpen(false);
  };

  const formatDate = (date: Date) => {
    const day = String(date.getDate()).padStart(2, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const year = date.getFullYear();
    return `${day}/${month}/${year}`;
  };

  const renderWBSItem = (item: WBSItem) => {
    const isExpanded = expandedItems.has(item.id);
    const hasChildren = item.children.length > 0;
    const StatusIcon = getStatusIcon(item.status);
    const statusColor = getStatusColor(item.status);

    return (
      <div key={item.id}>
        <div className="flex items-center py-3 px-4 hover:bg-muted/50 border-b border-border">
          {/* Expand/Collapse Button */}
          <div className="w-8 flex justify-center">
            {hasChildren ? (
              <Button
                variant="ghost"
                size="sm"
                className="h-6 w-6 p-0"
                onClick={() => toggleExpanded(item.id)}
              >
                {isExpanded ? (
                  <ChevronDown className="h-4 w-4" />
                ) : (
                  <ChevronRight className="h-4 w-4" />
                )}
              </Button>
            ) : null}
          </div>

          {/* Status Icon */}
          <div className="w-8 flex justify-center">
            <StatusIcon className={`h-5 w-5 ${statusColor}`} />
          </div>

          {/* Task Code */}
          <div className="w-20">
            <span className="text-sm text-muted-foreground tabular-nums">{item.code}</span>
          </div>

          {/* Task Title and Description */}
          <div className="flex-1 min-w-0 px-4">
            <div className="font-medium text-foreground truncate">{item.title}</div>
            {item.description && (
              <div className="text-sm text-muted-foreground truncate">{item.description}</div>
            )}
          </div>

          {/* Assignee */}
          <div className="w-32">
            {item.assignedTo && (
              <div className="flex items-center space-x-2">
                <div className="h-6 w-6 rounded-full bg-primary/15 flex items-center justify-center">
                  <span className="text-xs font-medium text-primary">
                    {getInitials(getUserName(item.assignedTo))}
                  </span>
                </div>
                <span className="text-sm text-foreground/80 truncate">
                  {getUserName(item.assignedTo)}
                </span>
              </div>
            )}
          </div>

          {/* Estimated Hours */}
          <div className="w-24 text-center">
            {item.estimatedHours && (
              <span className="text-sm text-muted-foreground">{item.estimatedHours}h</span>
            )}
          </div>

          {/* Dates */}
          <div className="w-32 text-center">
            {item.startDate && (
              <div className="text-sm text-muted-foreground">
                {formatDate(item.startDate)}
                {item.endDate && (
                  <span className="text-muted-foreground"> - {formatDate(item.endDate)}</span>
                )}
              </div>
            )}
          </div>

          {/* Actions */}
          <div className="w-12 flex justify-center">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
                  <MoreHorizontal className="h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem onClick={() => {
                  setSelectedParent(item.id);
                  setCreateType('sub');
                  setIsCreateDialogOpen(true);
                }}>
                  <Plus className="h-4 w-4 mr-2" />
                  Add Subtask
                </DropdownMenuItem>
                <DropdownMenuItem>
                  <Edit className="h-4 w-4 mr-2" />
                  Edit
                </DropdownMenuItem>
                <DropdownMenuItem className="text-red-600">
                  <Trash2 className="h-4 w-4 mr-2" />
                  Delete
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
        
        {hasChildren && isExpanded && (
          <div className="ml-8">
            {item.children.map(child => renderWBSItem(child))}
          </div>
        )}
      </div>
    );
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-foreground">Work Breakdown Structure</h2>
          <p className="text-muted-foreground">Organize project tasks in a hierarchical structure</p>
        </div>
        <div className="flex items-center space-x-2">
          <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
            <DialogTrigger asChild>
              <Button 
                variant="outline"
                onClick={() => {
                  setSelectedParent(null);
                  setCreateType('main');
                }}
              >
                <Plus className="h-4 w-4 mr-2" />
                Add Main Task
              </Button>
            </DialogTrigger>
            <DialogTrigger asChild>
              <Button onClick={() => {
                setSelectedParent(null);
                setCreateType('sub');
              }}>
                <Plus className="h-4 w-4 mr-2" />
                Add Subtask
              </Button>
            </DialogTrigger>
            
            <DialogContent className="max-w-2xl">
              <DialogHeader>
                <DialogTitle>
                  {createType === 'main' ? 'Add Main Task' : selectedParent ? 'Add Subtask' : 'Add New Task'}
                </DialogTitle>
              </DialogHeader>
              <div className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="title">Task Title</Label>
                  <Input
                    id="title"
                    value={newItem.title}
                    onChange={(e) => setNewItem(prev => ({ ...prev, title: e.target.value }))}
                    placeholder="Enter task title"
                  />
                </div>
                
                <div className="space-y-2">
                  <Label htmlFor="description">Description</Label>
                  <Textarea
                    id="description"
                    value={newItem.description}
                    onChange={(e) => setNewItem(prev => ({ ...prev, description: e.target.value }))}
                    placeholder="Enter task description"
                    rows={3}
                  />
                </div>
                
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="assignedTo">Assigned To</Label>
                    <Select
                      value={newItem.assignedTo}
                      onValueChange={(value) => setNewItem(prev => ({ ...prev, assignedTo: value }))}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select assignee" />
                      </SelectTrigger>
                      <SelectContent>
                        {mockUsers.map((user) => (
                          <SelectItem key={user.id} value={user.id}>
                            {user.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  
                  <div className="space-y-2">
                    <Label htmlFor="estimatedHours">Estimated Hours</Label>
                    <Input
                      id="estimatedHours"
                      type="number"
                      value={newItem.estimatedHours}
                      onChange={(e) => setNewItem(prev => ({ ...prev, estimatedHours: e.target.value }))}
                      placeholder="0"
                    />
                  </div>
                </div>
                
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="startDate">Start Date</Label>
                    <DatePicker
                      id="startDate"
                      value={newItem.startDate}
                      onChange={(startDate) => setNewItem(prev => ({ ...prev, startDate }))}
                      clearable
                    />
                  </div>
                  
                  <div className="space-y-2">
                    <Label htmlFor="endDate">End Date</Label>
                    <DatePicker
                      id="endDate"
                      value={newItem.endDate}
                      onChange={(endDate) => setNewItem(prev => ({ ...prev, endDate }))}
                      clearable
                    />
                  </div>
                </div>
                
                <div className="flex justify-end space-x-2">
                  <Button variant="outline" onClick={() => setIsCreateDialogOpen(false)}>
                    Cancel
                  </Button>
                  <Button onClick={handleCreateItem}>
                    Create Task
                  </Button>
                </div>
              </div>
            </DialogContent>
          </Dialog>
        </div>
      </div>

      {/* WBS Table */}
      <Card className="overflow-hidden">
        {/* Table Header */}
        <div className="bg-muted/50 border-b border-border">
          <div className="flex items-center py-3 px-4 text-sm font-medium text-foreground/80">
            <div className="w-8"></div> {/* Expand/Collapse */}
            <div className="w-8"></div> {/* Status */}
            <div className="w-20">Code</div>
            <div className="flex-1 px-4">Task</div>
            <div className="w-32">Assignee</div>
            <div className="w-24 text-center">Hours</div>
            <div className="w-32 text-center">Timeline</div>
            <div className="w-12"></div> {/* Actions */}
          </div>
        </div>

        {/* Table Body */}
        <div className="divide-y divide-gray-100">
          {wbsItems.map(item => renderWBSItem(item))}
        </div>

        {wbsItems.length === 0 && (
          <div className="p-12 text-center">
            <div className="text-muted-foreground mb-4">
              <Circle className="h-12 w-12 mx-auto" />
            </div>
            <h3 className="text-lg font-semibold text-foreground mb-2">No tasks created yet</h3>
            <p className="text-muted-foreground mb-4">Start by creating your first main task to organize your project work.</p>
            <Button onClick={() => {
              setSelectedParent(null);
              setCreateType('main');
              setIsCreateDialogOpen(true);
            }}>
              <Plus className="h-4 w-4 mr-2" />
              Create First Task
            </Button>
          </div>
        )}
      </Card>
    </div>
  );
}