'use client';

import { useState } from 'react';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Search,
  Filter,
  ChevronRight,
  ArrowLeft,
  ChevronUp,
  ChevronDown,
  MoreVertical,
  CircleDot,
  PlayCircle,
  Clock,
  CheckCircle2,
  AlertCircle,
  XCircle,
  RefreshCw,
  ExternalLink,
  MessageSquare,
  GitBranch,
  GitPullRequest,
  Bot,
  User,
  Calendar,
  Tag,
  Settings,
  Upload,
  Trash2,
  Edit,
  Plus,
} from 'lucide-react';

// Mock data for issues
const mockIssues = [
  {
    id: 'ISS-001',
    number: 42,
    title: 'Implement user authentication flow',
    description: 'Create complete authentication flow with login, register, and password reset.',
    status: 'in_progress',
    priority: 'high',
    labels: ['feature', 'auth', 'backend'],
    sprint: 'Sprint 3',
    assignee: { name: 'Backend Engineer', type: 'agent' },
    createdAt: '2025-01-15',
    updatedAt: '2 hours ago',
    syncStatus: 'synced',
  },
  {
    id: 'ISS-002',
    number: 43,
    title: 'Design product catalog component',
    description: 'Create reusable product card and catalog grid components.',
    status: 'in_review',
    priority: 'medium',
    labels: ['feature', 'frontend', 'ui'],
    sprint: 'Sprint 3',
    assignee: { name: 'Frontend Engineer', type: 'agent' },
    createdAt: '2025-01-16',
    updatedAt: '30 min ago',
    syncStatus: 'synced',
  },
  {
    id: 'ISS-003',
    number: 44,
    title: 'Fix cart total calculation bug',
    description: 'Cart total shows incorrect amount when discount is applied.',
    status: 'blocked',
    priority: 'high',
    labels: ['bug', 'critical', 'backend'],
    sprint: 'Sprint 3',
    assignee: { name: 'Backend Engineer', type: 'agent' },
    createdAt: '2025-01-17',
    updatedAt: '1 hour ago',
    syncStatus: 'pending',
    blockedBy: 'Waiting for discount API specification',
  },
  {
    id: 'ISS-004',
    number: 45,
    title: 'Add product search functionality',
    description: 'Implement full-text search with filters for the product catalog.',
    status: 'open',
    priority: 'medium',
    labels: ['feature', 'search', 'backend'],
    sprint: 'Sprint 3',
    assignee: null,
    createdAt: '2025-01-18',
    updatedAt: '3 hours ago',
    syncStatus: 'synced',
  },
  {
    id: 'ISS-005',
    number: 46,
    title: 'Optimize database queries for product listing',
    description: 'Performance optimization for product queries with pagination.',
    status: 'done',
    priority: 'low',
    labels: ['performance', 'backend', 'database'],
    sprint: 'Sprint 2',
    assignee: { name: 'Backend Engineer', type: 'agent' },
    createdAt: '2025-01-10',
    updatedAt: '2 days ago',
    syncStatus: 'synced',
  },
  {
    id: 'ISS-006',
    number: 47,
    title: 'Create checkout page wireframes',
    description: 'Design wireframes for the checkout flow including payment selection.',
    status: 'done',
    priority: 'high',
    labels: ['design', 'checkout', 'ui'],
    sprint: 'Sprint 2',
    assignee: { name: 'Product Owner', type: 'agent' },
    createdAt: '2025-01-08',
    updatedAt: '5 days ago',
    syncStatus: 'synced',
  },
  {
    id: 'ISS-007',
    number: 48,
    title: 'Implement responsive navigation',
    description: 'Create mobile-friendly navigation with hamburger menu.',
    status: 'open',
    priority: 'medium',
    labels: ['feature', 'frontend', 'responsive'],
    sprint: null,
    assignee: null,
    createdAt: '2025-01-19',
    updatedAt: '1 day ago',
    syncStatus: 'synced',
  },
  {
    id: 'ISS-008',
    number: 49,
    title: 'Set up E2E test framework',
    description: 'Configure Playwright for end-to-end testing.',
    status: 'in_progress',
    priority: 'medium',
    labels: ['testing', 'infrastructure'],
    sprint: 'Sprint 3',
    assignee: { name: 'QA Engineer', type: 'agent' },
    createdAt: '2025-01-20',
    updatedAt: '4 hours ago',
    syncStatus: 'synced',
  },
];

// Detailed issue for detail view
const mockIssueDetail = {
  id: 'ISS-001',
  number: 42,
  title: 'Implement user authentication flow',
  description: `## Overview
Create a complete authentication flow for the e-commerce platform.

## Requirements
- Login with email/password
- Registration with email verification
- Password reset functionality
- OAuth support (Google, GitHub)
- JWT token management
- Session handling

## Acceptance Criteria
- [ ] Users can register with email and password
- [ ] Users receive email verification link
- [ ] Users can log in with verified email
- [ ] Password reset email is sent within 30 seconds
- [ ] OAuth buttons redirect properly
- [x] JWT tokens are stored securely
- [x] Tokens refresh automatically

## Technical Notes
- Use FastAPI security utilities
- Store sessions in Redis
- Follow OWASP guidelines
`,
  status: 'in_progress',
  priority: 'high',
  labels: ['feature', 'auth', 'backend', 'security'],
  sprint: 'Sprint 3',
  milestone: 'MVP Launch',
  storyPoints: 8,
  assignee: { name: 'Backend Engineer', type: 'agent', avatar: 'BE' },
  reporter: { name: 'Product Owner', type: 'agent', avatar: 'PO' },
  createdAt: '2025-01-15T10:30:00Z',
  updatedAt: '2025-01-20T14:22:00Z',
  dueDate: '2025-02-01',
  syncStatus: 'synced',
  externalUrl: 'https://gitea.example.com/project/issues/42',
  branch: 'feature/42-auth-flow',
  pullRequest: 'PR #15',
  activity: [
    {
      id: 'act-001',
      type: 'status_change',
      actor: { name: 'Backend Engineer', type: 'agent' },
      message: 'moved issue from "Open" to "In Progress"',
      timestamp: '2 hours ago',
    },
    {
      id: 'act-002',
      type: 'comment',
      actor: { name: 'Backend Engineer', type: 'agent' },
      message: 'Started implementing JWT token generation. Using HS256 algorithm as discussed in architecture meeting.',
      timestamp: '3 hours ago',
    },
    {
      id: 'act-003',
      type: 'assignment',
      actor: { name: 'Product Owner', type: 'agent' },
      message: 'assigned this issue to Backend Engineer',
      timestamp: '1 day ago',
    },
    {
      id: 'act-004',
      type: 'label',
      actor: { name: 'Product Owner', type: 'agent' },
      message: 'added labels: security, backend',
      timestamp: '1 day ago',
    },
    {
      id: 'act-005',
      type: 'created',
      actor: { name: 'Product Owner', type: 'agent' },
      message: 'created this issue',
      timestamp: '5 days ago',
    },
  ],
};

// Status config
const statusConfig: Record<string, { label: string; icon: typeof CircleDot; color: string }> = {
  open: { label: 'Open', icon: CircleDot, color: 'text-blue-500' },
  in_progress: { label: 'In Progress', icon: PlayCircle, color: 'text-yellow-500' },
  in_review: { label: 'In Review', icon: Clock, color: 'text-purple-500' },
  blocked: { label: 'Blocked', icon: AlertCircle, color: 'text-red-500' },
  done: { label: 'Done', icon: CheckCircle2, color: 'text-green-500' },
  closed: { label: 'Closed', icon: XCircle, color: 'text-gray-500' },
};

// Priority config
const priorityConfig: Record<string, { label: string; color: string }> = {
  high: { label: 'High', color: 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200' },
  medium: { label: 'Medium', color: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200' },
  low: { label: 'Low', color: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200' },
};

// Sync status indicator
function SyncStatusIndicator({ status }: { status: string }) {
  const configs: Record<string, { icon: typeof RefreshCw; color: string; label: string }> = {
    synced: { icon: CheckCircle2, color: 'text-green-500', label: 'Synced' },
    pending: { icon: RefreshCw, color: 'text-yellow-500 animate-spin', label: 'Syncing' },
    error: { icon: AlertCircle, color: 'text-red-500', label: 'Sync Error' },
  };
  const config = configs[status] || configs.synced;
  const Icon = config.icon;

  return (
    <div className="flex items-center gap-1" title={config.label}>
      <Icon className={`h-3.5 w-3.5 ${config.color}`} />
    </div>
  );
}

// Issue status badge
function StatusBadge({ status }: { status: string }) {
  const config = statusConfig[status] || statusConfig.open;
  const Icon = config.icon;

  return (
    <div className={`flex items-center gap-1.5 ${config.color}`}>
      <Icon className="h-4 w-4" />
      <span className="text-sm font-medium">{config.label}</span>
    </div>
  );
}

// Priority badge
function PriorityBadge({ priority }: { priority: string }) {
  const config = priorityConfig[priority] || priorityConfig.medium;
  return (
    <Badge className={config.color} variant="outline">
      {config.label}
    </Badge>
  );
}

// Issue List View
function IssueListView({ onSelectIssue }: { onSelectIssue: (id: string) => void }) {
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [priorityFilter, setPriorityFilter] = useState('all');
  const [sprintFilter, setSprintFilter] = useState('all');
  const [selectedIssues, setSelectedIssues] = useState<string[]>([]);
  const [sortField, setSortField] = useState<'number' | 'priority' | 'updatedAt'>('updatedAt');
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc');
  const [showFilters, setShowFilters] = useState(false);

  const filteredIssues = mockIssues.filter((issue) => {
    const matchesSearch =
      issue.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      issue.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
      issue.number.toString().includes(searchQuery);
    const matchesStatus = statusFilter === 'all' || issue.status === statusFilter;
    const matchesPriority = priorityFilter === 'all' || issue.priority === priorityFilter;
    const matchesSprint =
      sprintFilter === 'all' ||
      (sprintFilter === 'backlog' && !issue.sprint) ||
      issue.sprint === sprintFilter;
    return matchesSearch && matchesStatus && matchesPriority && matchesSprint;
  });

  const sortedIssues = [...filteredIssues].sort((a, b) => {
    const direction = sortDirection === 'asc' ? 1 : -1;
    if (sortField === 'number') return (a.number - b.number) * direction;
    if (sortField === 'priority') {
      const priorityOrder = { high: 3, medium: 2, low: 1 };
      return (priorityOrder[a.priority as keyof typeof priorityOrder] -
        priorityOrder[b.priority as keyof typeof priorityOrder]) * direction;
    }
    return 0; // Default to original order for updatedAt
  });

  const handleSort = (field: 'number' | 'priority' | 'updatedAt') => {
    if (sortField === field) {
      setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortDirection('desc');
    }
  };

  const handleSelectAll = () => {
    if (selectedIssues.length === sortedIssues.length) {
      setSelectedIssues([]);
    } else {
      setSelectedIssues(sortedIssues.map((i) => i.id));
    }
  };

  const handleSelectIssue = (id: string) => {
    if (selectedIssues.includes(id)) {
      setSelectedIssues(selectedIssues.filter((i) => i !== id));
    } else {
      setSelectedIssues([...selectedIssues, id]);
    }
  };

  const SortIcon = ({ field }: { field: string }) => {
    if (sortField !== field) return null;
    return sortDirection === 'asc' ? (
      <ChevronUp className="ml-1 inline h-4 w-4" />
    ) : (
      <ChevronDown className="ml-1 inline h-4 w-4" />
    );
  };

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-3xl font-bold">Issues</h1>
          <p className="text-muted-foreground">
            {filteredIssues.length} issues found
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm">
            <Upload className="mr-2 h-4 w-4" />
            Sync
          </Button>
          <Button size="sm">
            <Plus className="mr-2 h-4 w-4" />
            New Issue
          </Button>
        </div>
      </div>

      {/* Search and Quick Filters */}
      <div className="flex flex-col gap-4 sm:flex-row">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder="Search issues..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-9"
          />
        </div>
        <div className="flex gap-2">
          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger className="w-32">
              <SelectValue placeholder="Status" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Status</SelectItem>
              <SelectItem value="open">Open</SelectItem>
              <SelectItem value="in_progress">In Progress</SelectItem>
              <SelectItem value="in_review">In Review</SelectItem>
              <SelectItem value="blocked">Blocked</SelectItem>
              <SelectItem value="done">Done</SelectItem>
            </SelectContent>
          </Select>
          <Button
            variant="outline"
            size="icon"
            onClick={() => setShowFilters(!showFilters)}
            className={showFilters ? 'bg-muted' : ''}
          >
            <Filter className="h-4 w-4" />
          </Button>
        </div>
      </div>

      {/* Extended Filters */}
      {showFilters && (
        <Card className="p-4">
          <div className="grid gap-4 sm:grid-cols-4">
            <div className="space-y-2">
              <Label>Priority</Label>
              <Select value={priorityFilter} onValueChange={setPriorityFilter}>
                <SelectTrigger>
                  <SelectValue placeholder="All" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All</SelectItem>
                  <SelectItem value="high">High</SelectItem>
                  <SelectItem value="medium">Medium</SelectItem>
                  <SelectItem value="low">Low</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Sprint</Label>
              <Select value={sprintFilter} onValueChange={setSprintFilter}>
                <SelectTrigger>
                  <SelectValue placeholder="All" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Sprints</SelectItem>
                  <SelectItem value="Sprint 3">Sprint 3</SelectItem>
                  <SelectItem value="Sprint 2">Sprint 2</SelectItem>
                  <SelectItem value="backlog">Backlog</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Assignee</Label>
              <Select defaultValue="all">
                <SelectTrigger>
                  <SelectValue placeholder="All" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All</SelectItem>
                  <SelectItem value="unassigned">Unassigned</SelectItem>
                  <SelectItem value="backend">Backend Engineer</SelectItem>
                  <SelectItem value="frontend">Frontend Engineer</SelectItem>
                  <SelectItem value="qa">QA Engineer</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Labels</Label>
              <Select defaultValue="all">
                <SelectTrigger>
                  <SelectValue placeholder="All" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All</SelectItem>
                  <SelectItem value="feature">Feature</SelectItem>
                  <SelectItem value="bug">Bug</SelectItem>
                  <SelectItem value="backend">Backend</SelectItem>
                  <SelectItem value="frontend">Frontend</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <div className="mt-4 flex justify-end gap-2">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => {
                setStatusFilter('all');
                setPriorityFilter('all');
                setSprintFilter('all');
              }}
            >
              Clear Filters
            </Button>
          </div>
        </Card>
      )}

      {/* Bulk Actions */}
      {selectedIssues.length > 0 && (
        <div className="flex items-center gap-4 rounded-lg border bg-muted/50 p-3">
          <span className="text-sm font-medium">
            {selectedIssues.length} selected
          </span>
          <Separator orientation="vertical" className="h-6" />
          <div className="flex gap-2">
            <Button variant="outline" size="sm">
              Change Status
            </Button>
            <Button variant="outline" size="sm">
              Assign
            </Button>
            <Button variant="outline" size="sm">
              Add Labels
            </Button>
            <Button variant="outline" size="sm" className="text-destructive">
              <Trash2 className="mr-2 h-4 w-4" />
              Delete
            </Button>
          </div>
        </div>
      )}

      {/* Issue Table */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-12">
                <Checkbox
                  checked={
                    selectedIssues.length === sortedIssues.length && sortedIssues.length > 0
                  }
                  onCheckedChange={handleSelectAll}
                />
              </TableHead>
              <TableHead
                className="w-20 cursor-pointer"
                onClick={() => handleSort('number')}
              >
                # <SortIcon field="number" />
              </TableHead>
              <TableHead>Title</TableHead>
              <TableHead className="w-32">Status</TableHead>
              <TableHead
                className="w-24 cursor-pointer"
                onClick={() => handleSort('priority')}
              >
                Priority <SortIcon field="priority" />
              </TableHead>
              <TableHead className="w-32">Assignee</TableHead>
              <TableHead className="w-28">Sprint</TableHead>
              <TableHead className="w-10">Sync</TableHead>
              <TableHead className="w-10"></TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {sortedIssues.map((issue) => (
              <TableRow
                key={issue.id}
                className="cursor-pointer"
                onClick={() => onSelectIssue(issue.id)}
              >
                <TableCell onClick={(e) => e.stopPropagation()}>
                  <Checkbox
                    checked={selectedIssues.includes(issue.id)}
                    onCheckedChange={() => handleSelectIssue(issue.id)}
                  />
                </TableCell>
                <TableCell className="font-mono text-sm text-muted-foreground">
                  {issue.number}
                </TableCell>
                <TableCell>
                  <div className="space-y-1">
                    <p className="font-medium">{issue.title}</p>
                    <div className="flex flex-wrap gap-1">
                      {issue.labels.slice(0, 3).map((label) => (
                        <Badge key={label} variant="secondary" className="text-xs">
                          {label}
                        </Badge>
                      ))}
                      {issue.labels.length > 3 && (
                        <Badge variant="outline" className="text-xs">
                          +{issue.labels.length - 3}
                        </Badge>
                      )}
                    </div>
                  </div>
                </TableCell>
                <TableCell>
                  <StatusBadge status={issue.status} />
                </TableCell>
                <TableCell>
                  <PriorityBadge priority={issue.priority} />
                </TableCell>
                <TableCell>
                  {issue.assignee ? (
                    <div className="flex items-center gap-2">
                      <div className="flex h-6 w-6 items-center justify-center rounded-full bg-primary/10 text-xs font-medium text-primary">
                        {issue.assignee.type === 'agent' ? (
                          <Bot className="h-3 w-3" />
                        ) : (
                          <User className="h-3 w-3" />
                        )}
                      </div>
                      <span className="text-sm">{issue.assignee.name}</span>
                    </div>
                  ) : (
                    <span className="text-sm text-muted-foreground">Unassigned</span>
                  )}
                </TableCell>
                <TableCell>
                  {issue.sprint ? (
                    <Badge variant="outline" className="text-xs">
                      {issue.sprint}
                    </Badge>
                  ) : (
                    <span className="text-xs text-muted-foreground">Backlog</span>
                  )}
                </TableCell>
                <TableCell>
                  <SyncStatusIndicator status={issue.syncStatus} />
                </TableCell>
                <TableCell onClick={(e) => e.stopPropagation()}>
                  <Button variant="ghost" size="icon" className="h-8 w-8">
                    <MoreVertical className="h-4 w-4" />
                  </Button>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>

        {sortedIssues.length === 0 && (
          <div className="py-12 text-center">
            <CircleDot className="mx-auto h-12 w-12 text-muted-foreground" />
            <h3 className="mt-4 font-semibold">No issues found</h3>
            <p className="text-muted-foreground">Try adjusting your search or filters</p>
          </div>
        )}
      </Card>
    </div>
  );
}

// Issue Detail View
function IssueDetailView({ onBack }: { onBack: () => void }) {
  const issue = mockIssueDetail;
  const [currentStatus, setCurrentStatus] = useState(issue.status);

  const workflowButtons = [
    { from: 'open', to: 'in_progress', label: 'Start Work' },
    { from: 'in_progress', to: 'in_review', label: 'Submit for Review' },
    { from: 'in_review', to: 'done', label: 'Mark Done' },
    { from: 'blocked', to: 'in_progress', label: 'Unblock' },
  ];

  const currentWorkflow = workflowButtons.find((w) => w.from === currentStatus);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-start gap-4">
        <Button variant="ghost" size="icon" onClick={onBack}>
          <ArrowLeft className="h-4 w-4" />
        </Button>
        <div className="flex-1 space-y-2">
          <div className="flex flex-wrap items-center gap-2">
            <span className="font-mono text-muted-foreground">#{issue.number}</span>
            <StatusBadge status={currentStatus} />
            <PriorityBadge priority={issue.priority} />
            <SyncStatusIndicator status={issue.syncStatus} />
          </div>
          <h1 className="text-2xl font-bold">{issue.title}</h1>
          <div className="flex flex-wrap items-center gap-4 text-sm text-muted-foreground">
            <div className="flex items-center gap-1">
              <Calendar className="h-4 w-4" />
              Created {new Date(issue.createdAt).toLocaleDateString()}
            </div>
            <div className="flex items-center gap-1">
              <Clock className="h-4 w-4" />
              Updated {new Date(issue.updatedAt).toLocaleDateString()}
            </div>
            {issue.externalUrl && (
              <a
                href={issue.externalUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="flex items-center gap-1 text-primary hover:underline"
              >
                <ExternalLink className="h-4 w-4" />
                View in Gitea
              </a>
            )}
          </div>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm">
            <Edit className="mr-2 h-4 w-4" />
            Edit
          </Button>
          {currentWorkflow && (
            <Button size="sm" onClick={() => setCurrentStatus(currentWorkflow.to)}>
              {currentWorkflow.label}
            </Button>
          )}
        </div>
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        {/* Main Content */}
        <div className="space-y-6 lg:col-span-2">
          {/* Description Card */}
          <Card>
            <CardHeader>
              <CardTitle>Description</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="prose prose-sm max-w-none dark:prose-invert">
                <pre className="whitespace-pre-wrap font-sans text-sm">
                  {issue.description}
                </pre>
              </div>
            </CardContent>
          </Card>

          {/* Activity Timeline */}
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="flex items-center gap-2">
                  <MessageSquare className="h-5 w-5" />
                  Activity
                </CardTitle>
                <Button variant="outline" size="sm">
                  Add Comment
                </Button>
              </div>
            </CardHeader>
            <CardContent>
              <div className="space-y-6">
                {issue.activity.map((item, index) => (
                  <div key={item.id} className="flex gap-4">
                    <div className="relative flex flex-col items-center">
                      <div className="flex h-8 w-8 items-center justify-center rounded-full bg-muted">
                        {item.actor.type === 'agent' ? (
                          <Bot className="h-4 w-4" />
                        ) : (
                          <User className="h-4 w-4" />
                        )}
                      </div>
                      {index < issue.activity.length - 1 && (
                        <div className="absolute top-8 h-full w-px bg-border" />
                      )}
                    </div>
                    <div className="flex-1 pb-6">
                      <div className="flex items-baseline gap-2">
                        <span className="font-medium">{item.actor.name}</span>
                        <span className="text-sm text-muted-foreground">
                          {item.message}
                        </span>
                      </div>
                      <p className="text-xs text-muted-foreground">{item.timestamp}</p>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Status Actions */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">Status Workflow</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                {Object.entries(statusConfig).map(([key, config]) => {
                  const Icon = config.icon;
                  const isActive = currentStatus === key;
                  return (
                    <button
                      key={key}
                      className={`flex w-full items-center gap-2 rounded-lg p-2 text-left transition-colors ${
                        isActive
                          ? 'bg-primary/10 text-primary'
                          : 'hover:bg-muted'
                      }`}
                      onClick={() => setCurrentStatus(key)}
                    >
                      <Icon className={`h-4 w-4 ${config.color}`} />
                      <span className="text-sm">{config.label}</span>
                      {isActive && <CheckCircle2 className="ml-auto h-4 w-4" />}
                    </button>
                  );
                })}
              </div>
            </CardContent>
          </Card>

          {/* Assignment Panel */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">Details</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <p className="text-sm text-muted-foreground">Assignee</p>
                <div className="mt-1 flex items-center gap-2">
                  <div className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/10 text-sm font-medium text-primary">
                    {issue.assignee.avatar}
                  </div>
                  <div>
                    <p className="font-medium">{issue.assignee.name}</p>
                    <p className="text-xs text-muted-foreground">Agent</p>
                  </div>
                </div>
              </div>

              <Separator />

              <div>
                <p className="text-sm text-muted-foreground">Reporter</p>
                <div className="mt-1 flex items-center gap-2">
                  <div className="flex h-8 w-8 items-center justify-center rounded-full bg-muted text-sm font-medium">
                    {issue.reporter.avatar}
                  </div>
                  <p className="font-medium">{issue.reporter.name}</p>
                </div>
              </div>

              <Separator />

              <div>
                <p className="text-sm text-muted-foreground">Sprint</p>
                <p className="font-medium">{issue.sprint}</p>
              </div>

              <div>
                <p className="text-sm text-muted-foreground">Story Points</p>
                <p className="font-medium">{issue.storyPoints}</p>
              </div>

              <div>
                <p className="text-sm text-muted-foreground">Due Date</p>
                <p className="font-medium">{new Date(issue.dueDate).toLocaleDateString()}</p>
              </div>

              <Separator />

              <div>
                <p className="text-sm text-muted-foreground">Labels</p>
                <div className="mt-2 flex flex-wrap gap-1">
                  {issue.labels.map((label) => (
                    <Badge key={label} variant="secondary" className="text-xs">
                      <Tag className="mr-1 h-3 w-3" />
                      {label}
                    </Badge>
                  ))}
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Development */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">Development</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center gap-2">
                <GitBranch className="h-4 w-4 text-muted-foreground" />
                <span className="text-sm font-mono">{issue.branch}</span>
              </div>
              <div className="flex items-center gap-2">
                <GitPullRequest className="h-4 w-4 text-muted-foreground" />
                <span className="text-sm">{issue.pullRequest}</span>
                <Badge variant="outline" className="text-xs">Open</Badge>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}

export default function IssueManagementPrototype() {
  const [view, setView] = useState<'list' | 'detail'>('list');
  const [_selectedIssueId, setSelectedIssueId] = useState<string | null>(null);

  const handleSelectIssue = (id: string) => {
    setSelectedIssueId(id);
    setView('detail');
  };

  const handleBack = () => {
    setView('list');
    setSelectedIssueId(null);
  };

  return (
    <div className="min-h-screen bg-background">
      {/* Navigation Bar */}
      <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">E-Commerce Platform</span>
            <ChevronRight className="h-4 w-4 text-muted-foreground" />
            <span className="text-sm font-medium">Issues</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">
        {view === 'list' && <IssueListView onSelectIssue={handleSelectIssue} />}
        {view === 'detail' && <IssueDetailView onBack={handleBack} />}
      </div>
    </div>
  );
}
