'use client';

import { useState } from 'react';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import {
  Bot,
  Activity,
  AlertCircle,
  CheckCircle2,
  Clock,
  PlayCircle,
  PauseCircle,
  Settings,
  MessageSquare,
  GitPullRequest,
  GitBranch,
  MoreVertical,
  TrendingUp,
  Users,
  CircleDot,
  ChevronRight,
} from 'lucide-react';

// Mock data for the prototype
const mockProject = {
  id: 'proj-001',
  name: 'E-Commerce Platform Redesign',
  description: 'Complete redesign of the e-commerce platform with modern UI/UX',
  status: 'in_progress',
  autonomyLevel: 'milestone',
  currentSprint: 'Sprint 3',
  sprintProgress: 67,
  startDate: '2025-01-15',
  estimatedEnd: '2025-03-15',
};

const mockAgents = [
  {
    id: 'agent-001',
    name: 'Product Owner',
    type: 'product_owner',
    status: 'active',
    currentTask: 'Reviewing user story acceptance criteria',
    lastActivity: '2 min ago',
    avatar: 'PO',
  },
  {
    id: 'agent-002',
    name: 'Architect',
    type: 'architect',
    status: 'active',
    currentTask: 'Designing API contract for checkout flow',
    lastActivity: '5 min ago',
    avatar: 'AR',
  },
  {
    id: 'agent-003',
    name: 'Backend Engineer',
    type: 'engineer',
    status: 'idle',
    currentTask: 'Waiting for architecture review',
    lastActivity: '15 min ago',
    avatar: 'BE',
  },
  {
    id: 'agent-004',
    name: 'Frontend Engineer',
    type: 'engineer',
    status: 'active',
    currentTask: 'Implementing product catalog component',
    lastActivity: '1 min ago',
    avatar: 'FE',
  },
  {
    id: 'agent-005',
    name: 'QA Engineer',
    type: 'qa',
    status: 'pending',
    currentTask: 'Preparing test cases for Sprint 3',
    lastActivity: '30 min ago',
    avatar: 'QA',
  },
];

const mockSprintData = {
  name: 'Sprint 3',
  startDate: '2025-01-27',
  endDate: '2025-02-10',
  totalIssues: 15,
  completed: 8,
  inProgress: 4,
  blocked: 1,
  todo: 2,
  burndown: [
    { day: 1, remaining: 45, ideal: 45 },
    { day: 2, remaining: 42, ideal: 42 },
    { day: 3, remaining: 38, ideal: 39 },
    { day: 4, remaining: 35, ideal: 36 },
    { day: 5, remaining: 30, ideal: 33 },
    { day: 6, remaining: 28, ideal: 30 },
    { day: 7, remaining: 25, ideal: 27 },
    { day: 8, remaining: 20, ideal: 24 },
  ],
};

const mockActivity = [
  {
    id: 'act-001',
    type: 'agent_message',
    agent: 'Product Owner',
    message: 'Approved user story #42: Cart checkout flow',
    timestamp: '2 min ago',
    icon: MessageSquare,
  },
  {
    id: 'act-002',
    type: 'issue_update',
    agent: 'Backend Engineer',
    message: 'Moved issue #38 to "In Review"',
    timestamp: '8 min ago',
    icon: GitPullRequest,
  },
  {
    id: 'act-003',
    type: 'agent_status',
    agent: 'Frontend Engineer',
    message: 'Started working on issue #45',
    timestamp: '15 min ago',
    icon: PlayCircle,
  },
  {
    id: 'act-004',
    type: 'approval_request',
    agent: 'Architect',
    message: 'Requesting approval for API design document',
    timestamp: '25 min ago',
    icon: AlertCircle,
    requiresAction: true,
  },
  {
    id: 'act-005',
    type: 'sprint_event',
    agent: 'System',
    message: 'Sprint 3 daily standup completed',
    timestamp: '1 hour ago',
    icon: Users,
  },
];

const mockIssueSummary = {
  open: 12,
  inProgress: 8,
  inReview: 3,
  blocked: 2,
  done: 45,
  total: 70,
};

// Status badge component
function StatusBadge({ status }: { status: string }) {
  const variants: Record<string, { label: string; className: string }> = {
    in_progress: {
      label: 'In Progress',
      className: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200',
    },
    completed: {
      label: 'Completed',
      className: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200',
    },
    paused: {
      label: 'Paused',
      className: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200',
    },
    blocked: {
      label: 'Blocked',
      className: 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200',
    },
  };

  const variant = variants[status] || variants.in_progress;

  return (
    <Badge className={variant.className} variant="outline">
      {variant.label}
    </Badge>
  );
}

// Autonomy level badge
function AutonomyBadge({ level }: { level: string }) {
  const variants: Record<string, { label: string; description: string }> = {
    full_control: { label: 'Full Control', description: 'Approve every action' },
    milestone: { label: 'Milestone', description: 'Approve at sprint boundaries' },
    autonomous: { label: 'Autonomous', description: 'Only major decisions' },
  };

  const variant = variants[level] || variants.milestone;

  return (
    <Badge variant="secondary" className="gap-1">
      <CircleDot className="h-3 w-3" />
      {variant.label}
    </Badge>
  );
}

// Agent status indicator
function AgentStatusIndicator({ status }: { status: string }) {
  const colors: Record<string, string> = {
    active: 'bg-green-500',
    idle: 'bg-yellow-500',
    pending: 'bg-gray-400',
    error: 'bg-red-500',
  };

  return (
    <span
      className={`inline-block h-2 w-2 rounded-full ${colors[status] || colors.pending}`}
      aria-label={`Status: ${status}`}
    />
  );
}

// Simple burndown chart visualization
function BurndownChart({ data }: { data: typeof mockSprintData.burndown }) {
  const maxPoints = Math.max(...data.map((d) => Math.max(d.remaining, d.ideal)));
  const chartHeight = 120;
  const chartWidth = 100;

  return (
    <div className="relative h-32 w-full">
      <svg
        viewBox={`0 0 ${chartWidth} ${chartHeight}`}
        className="h-full w-full"
        preserveAspectRatio="none"
      >
        {/* Ideal line */}
        <polyline
          fill="none"
          stroke="currentColor"
          strokeOpacity="0.3"
          strokeWidth="1"
          strokeDasharray="4,2"
          points={data
            .map(
              (d, i) =>
                `${(i / (data.length - 1)) * chartWidth},${chartHeight - (d.ideal / maxPoints) * chartHeight}`
            )
            .join(' ')}
        />
        {/* Actual line */}
        <polyline
          fill="none"
          stroke="currentColor"
          className="text-primary"
          strokeWidth="2"
          points={data
            .map(
              (d, i) =>
                `${(i / (data.length - 1)) * chartWidth},${chartHeight - (d.remaining / maxPoints) * chartHeight}`
            )
            .join(' ')}
        />
      </svg>
      <div className="absolute bottom-0 left-0 right-0 flex justify-between text-xs text-muted-foreground">
        <span>Day 1</span>
        <span>Day {data.length}</span>
      </div>
    </div>
  );
}

// Progress bar component
function ProgressBar({ value, className }: { value: number; className?: string }) {
  return (
    <div className={`h-2 w-full rounded-full bg-muted ${className}`}>
      <div
        className="h-full rounded-full bg-primary transition-all"
        style={{ width: `${Math.min(100, Math.max(0, value))}%` }}
      />
    </div>
  );
}

export default function ProjectDashboardPrototype() {
  const [_selectedView, _setSelectedView] = useState('overview');

  return (
    <div className="min-h-screen bg-background">
      {/* Navigation Bar - Prototype placeholder */}
      <nav className="border-b bg-card">
        <div className="container mx-auto flex h-14 items-center justify-between px-4">
          <div className="flex items-center gap-4">
            <span className="font-semibold text-primary">Syndarix</span>
            <Separator orientation="vertical" className="h-6" />
            <span className="text-sm text-muted-foreground">Projects</span>
            <ChevronRight className="h-4 w-4 text-muted-foreground" />
            <span className="text-sm font-medium">{mockProject.name}</span>
          </div>
          <div className="flex items-center gap-2">
            <Button variant="ghost" size="icon">
              <Settings className="h-4 w-4" />
            </Button>
          </div>
        </div>
      </nav>

      <div className="container mx-auto px-4 py-6">
        <div className="space-y-6">
          {/* Header Section */}
          <div className="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
            <div className="space-y-2">
              <div className="flex flex-wrap items-center gap-3">
                <h1 className="text-3xl font-bold">{mockProject.name}</h1>
                <StatusBadge status={mockProject.status} />
                <AutonomyBadge level={mockProject.autonomyLevel} />
              </div>
              <p className="text-muted-foreground">{mockProject.description}</p>
            </div>
            <div className="flex gap-2">
              <Button variant="outline" size="sm">
                <PauseCircle className="mr-2 h-4 w-4" />
                Pause Project
              </Button>
              <Button size="sm">
                <PlayCircle className="mr-2 h-4 w-4" />
                Run Sprint
              </Button>
            </div>
          </div>

          {/* Main Content Grid */}
          <div className="grid gap-6 lg:grid-cols-3">
            {/* Left Column - Agent Panel & Sprint Overview */}
            <div className="space-y-6 lg:col-span-2">
              {/* Agent Panel */}
              <Card>
                <CardHeader className="pb-3">
                  <div className="flex items-center justify-between">
                    <div>
                      <CardTitle className="flex items-center gap-2">
                        <Bot className="h-5 w-5" />
                        Active Agents
                      </CardTitle>
                      <CardDescription>
                        {mockAgents.filter((a) => a.status === 'active').length} of{' '}
                        {mockAgents.length} agents working
                      </CardDescription>
                    </div>
                    <Button variant="outline" size="sm">
                      Manage Agents
                    </Button>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    {mockAgents.map((agent) => (
                      <div
                        key={agent.id}
                        className="flex items-center justify-between rounded-lg border p-3 transition-colors hover:bg-muted/50"
                      >
                        <div className="flex items-center gap-3">
                          <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10 text-sm font-medium text-primary">
                            {agent.avatar}
                          </div>
                          <div>
                            <div className="flex items-center gap-2">
                              <span className="font-medium">{agent.name}</span>
                              <AgentStatusIndicator status={agent.status} />
                            </div>
                            <p className="text-sm text-muted-foreground">{agent.currentTask}</p>
                          </div>
                        </div>
                        <div className="flex items-center gap-2">
                          <span className="text-xs text-muted-foreground">{agent.lastActivity}</span>
                          <Button variant="ghost" size="icon" className="h-8 w-8">
                            <MoreVertical className="h-4 w-4" />
                          </Button>
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>

              {/* Sprint Overview */}
              <Card>
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <div>
                      <CardTitle className="flex items-center gap-2">
                        <TrendingUp className="h-5 w-5" />
                        Sprint Overview
                      </CardTitle>
                      <CardDescription>
                        {mockSprintData.name} ({mockSprintData.startDate} - {mockSprintData.endDate})
                      </CardDescription>
                    </div>
                    <Select defaultValue="current">
                      <SelectTrigger className="w-32">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="current">Current</SelectItem>
                        <SelectItem value="sprint-2">Sprint 2</SelectItem>
                        <SelectItem value="sprint-1">Sprint 1</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="space-y-6">
                    {/* Sprint Progress */}
                    <div className="space-y-2">
                      <div className="flex justify-between text-sm">
                        <span>Sprint Progress</span>
                        <span className="font-medium">{mockProject.sprintProgress}%</span>
                      </div>
                      <ProgressBar value={mockProject.sprintProgress} />
                    </div>

                    {/* Issue Stats Grid */}
                    <div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
                      <div className="rounded-lg border p-3 text-center">
                        <div className="text-2xl font-bold text-green-600">{mockSprintData.completed}</div>
                        <div className="text-xs text-muted-foreground">Completed</div>
                      </div>
                      <div className="rounded-lg border p-3 text-center">
                        <div className="text-2xl font-bold text-blue-600">{mockSprintData.inProgress}</div>
                        <div className="text-xs text-muted-foreground">In Progress</div>
                      </div>
                      <div className="rounded-lg border p-3 text-center">
                        <div className="text-2xl font-bold text-red-600">{mockSprintData.blocked}</div>
                        <div className="text-xs text-muted-foreground">Blocked</div>
                      </div>
                      <div className="rounded-lg border p-3 text-center">
                        <div className="text-2xl font-bold text-gray-600">{mockSprintData.todo}</div>
                        <div className="text-xs text-muted-foreground">To Do</div>
                      </div>
                    </div>

                    {/* Burndown Chart */}
                    <div className="space-y-2">
                      <h4 className="text-sm font-medium">Burndown Chart</h4>
                      <BurndownChart data={mockSprintData.burndown} />
                      <div className="flex items-center justify-center gap-6 text-xs text-muted-foreground">
                        <span className="flex items-center gap-1">
                          <span className="h-0.5 w-4 bg-primary" /> Actual
                        </span>
                        <span className="flex items-center gap-1">
                          <span className="h-0.5 w-4 border-t border-dashed border-muted-foreground" />{' '}
                          Ideal
                        </span>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* Right Column - Activity & Issue Summary */}
            <div className="space-y-6">
              {/* Issue Summary */}
              <Card>
                <CardHeader className="pb-3">
                  <CardTitle className="flex items-center gap-2 text-lg">
                    <GitBranch className="h-5 w-5" />
                    Issue Summary
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <CircleDot className="h-4 w-4 text-blue-500" />
                        <span className="text-sm">Open</span>
                      </div>
                      <span className="font-medium">{mockIssueSummary.open}</span>
                    </div>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <PlayCircle className="h-4 w-4 text-yellow-500" />
                        <span className="text-sm">In Progress</span>
                      </div>
                      <span className="font-medium">{mockIssueSummary.inProgress}</span>
                    </div>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <Clock className="h-4 w-4 text-purple-500" />
                        <span className="text-sm">In Review</span>
                      </div>
                      <span className="font-medium">{mockIssueSummary.inReview}</span>
                    </div>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <AlertCircle className="h-4 w-4 text-red-500" />
                        <span className="text-sm">Blocked</span>
                      </div>
                      <span className="font-medium">{mockIssueSummary.blocked}</span>
                    </div>
                    <Separator />
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <CheckCircle2 className="h-4 w-4 text-green-500" />
                        <span className="text-sm">Completed</span>
                      </div>
                      <span className="font-medium">{mockIssueSummary.done}</span>
                    </div>
                    <div className="pt-2">
                      <Button variant="outline" className="w-full" size="sm">
                        View All Issues
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* Recent Activity */}
              <Card>
                <CardHeader className="pb-3">
                  <div className="flex items-center justify-between">
                    <CardTitle className="flex items-center gap-2 text-lg">
                      <Activity className="h-5 w-5" />
                      Recent Activity
                    </CardTitle>
                    <Button variant="ghost" size="sm" className="text-xs">
                      View All
                    </Button>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    {mockActivity.map((activity) => {
                      const Icon = activity.icon;
                      return (
                        <div key={activity.id} className="flex gap-3">
                          <div
                            className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-full ${
                              activity.requiresAction
                                ? 'bg-yellow-100 text-yellow-600 dark:bg-yellow-900 dark:text-yellow-400'
                                : 'bg-muted text-muted-foreground'
                            }`}
                          >
                            <Icon className="h-4 w-4" />
                          </div>
                          <div className="min-w-0 flex-1">
                            <p className="text-sm">
                              <span className="font-medium">{activity.agent}</span>{' '}
                              <span className="text-muted-foreground">{activity.message}</span>
                            </p>
                            <p className="text-xs text-muted-foreground">{activity.timestamp}</p>
                            {activity.requiresAction && (
                              <Button variant="outline" size="sm" className="mt-2 h-7 text-xs">
                                Review Request
                              </Button>
                            )}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
