'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
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 { ProjectStatus, ProjectPriority } from '@/lib/types';
import { 
  ArrowLeft, 
  Calendar, 
  DollarSign, 
  Users, 
  Clock,
  Edit,
  FileText,
  Folder,
  Settings,
  BarChart3
} from 'lucide-react';
import { ScopeOfWork } from '@/components/project/scope-of-work';
import { DocsAndFiles } from '@/components/project/docs-and-files';
import { formatDate as formatDateUtil } from '@/lib/date-utils';

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];
};

interface ProjectDetailContentProps {
  projectId: string;
}

export function ProjectDetailContent({ projectId }: ProjectDetailContentProps) {
  const router = useRouter();
  
  // In a real app, you'd fetch the project by ID
  const project = mockProjects.find(p => p.id === projectId);
  
  if (!project) {
    return (
      <div className="min-h-screen bg-muted/50">
        <div className="max-w-7xl mx-auto p-8">
          <div className="flex items-center justify-center min-h-[400px]">
            <div className="text-center">
              <h2 className="text-2xl font-bold text-foreground mb-2">Project Not Found</h2>
              <p className="text-muted-foreground mb-4">The project you're looking for doesn't exist.</p>
              <Button onClick={() => router.push('/dashboard/projects')}>
                Back to Projects
              </Button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  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: 'long' });
  };

  return (
    <div className="min-h-screen bg-muted/50">
      <div className="max-w-7xl mx-auto p-8">
        <div className="space-y-8">
          {/* Header */}
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <Button
                variant="ghost"
                onClick={() => router.push('/dashboard/projects')}
                className="p-2"
              >
                <ArrowLeft className="h-5 w-5" />
              </Button>
              <div>
                <h1 className="text-3xl font-bold text-foreground">{project.name}</h1>
                <p className="text-muted-foreground mt-1">{PROJECT_TYPES[project.type]} • {project.team} Team</p>
              </div>
            </div>
            <div className="flex items-center space-x-3">
              <Link href={`/dashboard/projects/${projectId}/wbs`}>
                <Button variant="outline">
                  <BarChart3 className="h-4 w-4 mr-2" />
                  WBS
                </Button>
              </Link>
              <Button variant="outline">
                <Edit className="h-4 w-4 mr-2" />
                Edit Project
              </Button>
              <Button variant="outline">
                <Settings className="h-4 w-4 mr-2" />
                Settings
              </Button>
            </div>
          </div>

          {/* First Row - Project Overview & WBS Progress (50% each) */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
            {/* Left Column - Project Overview */}
            <Card className="p-6">
              <h3 className="text-lg font-semibold text-foreground mb-4">Project Overview</h3>
              
              <div className="space-y-4">
                <div>
                  <h4 className="text-sm font-medium text-foreground/80 mb-2">Description</h4>
                  <p className="text-muted-foreground leading-relaxed">{project.description}</p>
                </div>
                
                <div className="flex flex-wrap gap-2">
                  <Badge variant="outline" className={getStatusBadgeColor(project.status)}>
                    {PROJECT_STATUS[project.status]}
                  </Badge>
                  <Badge variant="outline" className={getPriorityBadgeColor(project.priority)}>
                    {PROJECT_PRIORITY[project.priority]} Priority
                  </Badge>
                  <Badge variant="outline" className="bg-primary/10 text-primary border-primary/20">
                    {PROJECT_TYPES[project.type]}
                  </Badge>
                </div>

                <div className="grid grid-cols-1 gap-3">
                  <div className="flex items-center space-x-3 p-3 bg-muted/50 rounded-lg">
                    <Calendar className="h-5 w-5 text-muted-foreground" />
                    <div>
                      <p className="text-sm font-medium text-foreground">Start Date</p>
                      <p className="text-sm text-muted-foreground">{formatDate(project.startDate)}</p>
                    </div>
                  </div>
                  
                  {project.endDate && (
                    <div className="flex items-center space-x-3 p-3 bg-muted/50 rounded-lg">
                      <Clock className="h-5 w-5 text-muted-foreground" />
                      <div>
                        <p className="text-sm font-medium text-foreground">End Date</p>
                        <p className="text-sm text-muted-foreground">{formatDate(project.endDate)}</p>
                      </div>
                    </div>
                  )}
                  
                  {project.budget && (
                    <div className="flex items-center space-x-3 p-3 bg-muted/50 rounded-lg">
                      <DollarSign className="h-5 w-5 text-muted-foreground" />
                      <div>
                        <p className="text-sm font-medium text-foreground">Budget</p>
                        <p className="text-sm text-muted-foreground">{formatCurrency(project.budget)}</p>
                      </div>
                    </div>
                  )}
                  
                  <div className="flex items-center space-x-3 p-3 bg-muted/50 rounded-lg">
                    <Users className="h-5 w-5 text-muted-foreground" />
                    <div className="flex-1">
                      <p className="text-sm font-medium text-foreground mb-2">Team Members</p>
                      <div className="flex -space-x-2">
                        {project.assignedUsers.slice(0, 4).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 > 4 && (
                          <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 - 4}
                            </span>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </Card>

            {/* Right Column - WBS Progress Widget */}
            <WBSProgressWidget 
              projectId={project.id} 
              variant="detailed" 
              showActions={true}
            />
          </div>

          {/* Second Row - Scope of Work & Docs & Files (50% each) */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
            {/* Left Column - Scope of Work */}
            <Card className="p-6">
              <div className="flex items-center space-x-3 mb-6">
                <div className="p-2 bg-green-50 rounded-lg">
                  <FileText className="h-5 w-5 text-green-600" />
                </div>
                <div>
                  <h3 className="text-lg font-semibold text-foreground">Scope of Work</h3>
                  <p className="text-sm text-muted-foreground">Project requirements and specifications</p>
                </div>
              </div>
              <ScopeOfWork projectId={project.id} />
            </Card>

            {/* Right Column - Docs & Files */}
            <Card className="p-6">
              <div className="flex items-center space-x-3 mb-6">
                <div className="p-2 bg-primary/5 rounded-lg">
                  <Folder className="h-5 w-5 text-primary" />
                </div>
                <div>
                  <h3 className="text-lg font-semibold text-foreground">Documents & Files</h3>
                  <p className="text-sm text-muted-foreground">Project files and resources</p>
                </div>
              </div>
              <DocsAndFiles projectId={project.id} />
            </Card>
          </div>
        </div>
      </div>
    </div>
  );
}