'use client';

/**
 * Issue Detail Page
 *
 * Displays full issue details with status workflow and activity timeline.
 *
 * @module app/[locale]/(authenticated)/projects/[id]/issues/[issueId]/page
 */

import { use } from 'react';
import Link from 'next/link';
import {
  ArrowLeft,
  Calendar,
  Clock,
  ExternalLink,
  Edit,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import {
  StatusBadge,
  PriorityBadge,
  SyncStatusIndicator,
  StatusWorkflow,
  ActivityTimeline,
  IssueDetailPanel,
  useIssue,
  useUpdateIssueStatus,
  getPrimaryTransition,
} from '@/features/issues';
import type { IssueStatus } from '@/features/issues';

interface IssueDetailPageProps {
  params: Promise<{
    locale: string;
    id: string;
    issueId: string;
  }>;
}

export default function IssueDetailPage({ params }: IssueDetailPageProps) {
  const { locale, id: projectId, issueId } = use(params);

  const { data: issue, isLoading, error } = useIssue(issueId);
  const updateStatus = useUpdateIssueStatus();

  const handleStatusChange = (status: IssueStatus) => {
    updateStatus.mutate({ issueId, status });
  };

  const primaryTransition = issue ? getPrimaryTransition(issue.status) : undefined;

  if (error) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="rounded-lg border border-destructive bg-destructive/10 p-6 text-center">
          <h2 className="text-lg font-semibold text-destructive">Error Loading Issue</h2>
          <p className="mt-2 text-sm text-muted-foreground">
            Failed to load issue details. Please try again later.
          </p>
          <div className="mt-4 flex justify-center gap-2">
            <Link href={`/${locale}/projects/${projectId}/issues`}>
              <Button variant="outline">Back to Issues</Button>
            </Link>
            <Button
              variant="outline"
              onClick={() => window.location.reload()}
            >
              Retry
            </Button>
          </div>
        </div>
      </div>
    );
  }

  if (isLoading || !issue) {
    return (
      <div className="container mx-auto px-4 py-6">
        <div className="space-y-6">
          <div className="flex items-start gap-4">
            <Skeleton className="h-10 w-10" />
            <div className="flex-1 space-y-2">
              <Skeleton className="h-6 w-48" />
              <Skeleton className="h-8 w-96" />
              <Skeleton className="h-4 w-64" />
            </div>
          </div>
          <div className="grid gap-6 lg:grid-cols-3">
            <div className="space-y-6 lg:col-span-2">
              <Skeleton className="h-64 w-full" />
              <Skeleton className="h-96 w-full" />
            </div>
            <div className="space-y-6">
              <Skeleton className="h-64 w-full" />
              <Skeleton className="h-48 w-full" />
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-6">
      <div className="space-y-6">
        {/* Header */}
        <div className="flex items-start gap-4">
          <Link href={`/${locale}/projects/${projectId}/issues`}>
            <Button variant="ghost" size="icon" aria-label="Back to issues">
              <ArrowLeft className="h-4 w-4" aria-hidden="true" />
            </Button>
          </Link>
          <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={issue.status} />
              <PriorityBadge priority={issue.priority} />
              <SyncStatusIndicator status={issue.sync_status} showLabel />
            </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" aria-hidden="true" />
                Created {new Date(issue.created_at).toLocaleDateString()}
              </div>
              <div className="flex items-center gap-1">
                <Clock className="h-4 w-4" aria-hidden="true" />
                Updated {new Date(issue.updated_at).toLocaleDateString()}
              </div>
              {issue.external_url && (
                <a
                  href={issue.external_url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center gap-1 text-primary hover:underline"
                >
                  <ExternalLink className="h-4 w-4" aria-hidden="true" />
                  View in Gitea
                </a>
              )}
            </div>
          </div>
          <div className="flex gap-2">
            <Button variant="outline" size="sm">
              <Edit className="mr-2 h-4 w-4" aria-hidden="true" />
              Edit
            </Button>
            {primaryTransition && (
              <Button
                size="sm"
                onClick={() => handleStatusChange(primaryTransition.to)}
                disabled={updateStatus.isPending}
              >
                {updateStatus.isPending ? 'Updating...' : primaryTransition.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 */}
            <ActivityTimeline
              activities={issue.activity}
              onAddComment={() => console.log('Add comment')}
            />
          </div>

          {/* Sidebar */}
          <div className="space-y-6">
            {/* Status Workflow */}
            <StatusWorkflow
              currentStatus={issue.status}
              onStatusChange={handleStatusChange}
              disabled={updateStatus.isPending}
            />

            {/* Issue Details */}
            <IssueDetailPanel issue={issue} />
          </div>
        </div>
      </div>
    </div>
  );
}
