'use client';

import { use, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import {
  ArrowLeft,
  Edit,
  Trash2,
  Loader2,
  Clock,
  Calendar,
  User,
  Layers,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useStory, useUpdateStory, useDeleteStory, useChangeStoryStatus } from '@/lib/hooks/use-stories';
import { useEpic } from '@/lib/hooks/use-epics';
import { useProject } from '@/lib/hooks/use-projects';
import { StoryForm } from '@/components/projects/story-form';
import { TaskList } from '@/components/tasks/task-list';
import { formatDistanceToNow } from 'date-fns';
import { toast } from 'sonner';
import type { WorkItemStatus, WorkItemPriority } from '@/types/project';

interface StoryDetailPageProps {
  params: Promise<{ id: string }>;
}

export default function StoryDetailPage({ params }: StoryDetailPageProps) {
  const { id: storyId } = use(params);
  const router = useRouter();
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);

  const { data: story, isLoading: storyLoading, error: storyError } = useStory(storyId);
  const { data: epic, isLoading: epicLoading } = useEpic(story?.epicId || '');
  const { data: project, isLoading: projectLoading } = useProject(story?.projectId || '');
  const updateStory = useUpdateStory();
  const deleteStory = useDeleteStory();
  const changeStatus = useChangeStoryStatus();

  const handleDeleteStory = async () => {
    try {
      await deleteStory.mutateAsync(storyId);
      toast.success('Story deleted successfully');
      // Navigate back to epic detail page
      router.push(`/epics/${story?.epicId}`);
    } catch (error) {
      const message = error instanceof Error ? error.message : 'Failed to delete story';
      toast.error(message);
    }
  };

  const handleStatusChange = async (status: WorkItemStatus) => {
    if (!story) return;
    try {
      await changeStatus.mutateAsync({ id: storyId, status });
    } catch (error) {
      const message = error instanceof Error ? error.message : 'Failed to update status';
      toast.error(message);
    }
  };

  const handlePriorityChange = async (priority: WorkItemPriority) => {
    if (!story) return;
    try {
      await updateStory.mutateAsync({
        id: storyId,
        data: { priority },
      });
    } catch (error) {
      const message = error instanceof Error ? error.message : 'Failed to update priority';
      toast.error(message);
    }
  };

  const getStatusColor = (status: WorkItemStatus) => {
    switch (status) {
      case 'Backlog':
        return 'secondary';
      case 'Todo':
        return 'outline';
      case 'InProgress':
        return 'default';
      case 'Done':
        return 'success' as any;
      default:
        return 'secondary';
    }
  };

  const getPriorityColor = (priority: WorkItemPriority) => {
    switch (priority) {
      case 'Low':
        return 'bg-blue-100 text-blue-700 hover:bg-blue-100';
      case 'Medium':
        return 'bg-yellow-100 text-yellow-700 hover:bg-yellow-100';
      case 'High':
        return 'bg-orange-100 text-orange-700 hover:bg-orange-100';
      case 'Critical':
        return 'bg-red-100 text-red-700 hover:bg-red-100';
      default:
        return 'secondary';
    }
  };

  // Loading state
  if (storyLoading || epicLoading || projectLoading) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-10 w-96" />
        <div className="flex items-start justify-between">
          <div className="space-y-4 flex-1">
            <Skeleton className="h-12 w-1/2" />
            <Skeleton className="h-20 w-full" />
          </div>
          <Skeleton className="h-10 w-32" />
        </div>
        <Skeleton className="h-64 w-full" />
      </div>
    );
  }

  // Error state
  if (storyError || !story) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <Card className="w-full max-w-md">
          <CardHeader>
            <CardTitle className="text-destructive">Error Loading Story</CardTitle>
            <CardDescription>
              {storyError instanceof Error ? storyError.message : 'Story not found'}
            </CardDescription>
          </CardHeader>
          <CardContent className="flex gap-2">
            <Button onClick={() => router.back()}>Go Back</Button>
            <Button onClick={() => window.location.reload()} variant="outline">
              Retry
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Breadcrumb Navigation */}
      <div className="flex items-center gap-2 text-sm text-muted-foreground">
        <Link href="/projects" className="hover:text-foreground">
          Projects
        </Link>
        <span>/</span>
        {project && (
          <>
            <Link href={`/projects/${project.id}`} className="hover:text-foreground">
              {project.name}
            </Link>
            <span>/</span>
          </>
        )}
        <Link href={`/projects/${story.projectId}/epics`} className="hover:text-foreground">
          Epics
        </Link>
        <span>/</span>
        {epic && (
          <>
            <Link href={`/epics/${epic.id}`} className="hover:text-foreground">
              {epic.name}
            </Link>
            <span>/</span>
          </>
        )}
        <span className="text-foreground">Stories</span>
        <span>/</span>
        <span className="text-foreground truncate max-w-[200px]" title={story.title}>
          {story.title}
        </span>
      </div>

      {/* Header */}
      <div className="flex items-start justify-between gap-4">
        <div className="space-y-2 flex-1">
          <div className="flex items-center gap-3">
            <Button
              variant="ghost"
              size="icon"
              onClick={() => router.push(`/epics/${story.epicId}`)}
              title="Back to Epic"
            >
              <ArrowLeft className="h-5 w-5" />
            </Button>
            <div className="flex-1">
              <h1 className="text-3xl font-bold tracking-tight">{story.title}</h1>
              <div className="flex items-center gap-2 mt-2 flex-wrap">
                <Badge variant={getStatusColor(story.status)}>{story.status}</Badge>
                <Badge className={getPriorityColor(story.priority)}>{story.priority}</Badge>
              </div>
            </div>
          </div>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={() => setIsEditDialogOpen(true)}>
            <Edit className="mr-2 h-4 w-4" />
            Edit Story
          </Button>
          <Button variant="destructive" onClick={() => setIsDeleteDialogOpen(true)}>
            <Trash2 className="mr-2 h-4 w-4" />
            Delete
          </Button>
        </div>
      </div>

      {/* Two-column layout */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Main Content Area (2/3 width) */}
        <div className="lg:col-span-2 space-y-6">
          {/* Story Details Card */}
          <Card>
            <CardHeader>
              <CardTitle>Story Details</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {story.description ? (
                <div>
                  <h3 className="text-sm font-medium text-muted-foreground mb-2">
                    Description
                  </h3>
                  <p className="text-sm whitespace-pre-wrap">{story.description}</p>
                </div>
              ) : (
                <p className="text-sm text-muted-foreground italic">No description</p>
              )}
            </CardContent>
          </Card>

          {/* Tasks Section - Sprint 4 Story 2 */}
          <TaskList storyId={storyId} />
        </div>

        {/* Metadata Sidebar (1/3 width) */}
        <div className="space-y-4">
          {/* Status */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm font-medium">Status</CardTitle>
            </CardHeader>
            <CardContent>
              <Select
                value={story.status}
                onValueChange={(value) => handleStatusChange(value as WorkItemStatus)}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="Backlog">Backlog</SelectItem>
                  <SelectItem value="Todo">Todo</SelectItem>
                  <SelectItem value="InProgress">In Progress</SelectItem>
                  <SelectItem value="Done">Done</SelectItem>
                </SelectContent>
              </Select>
            </CardContent>
          </Card>

          {/* Priority */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm font-medium">Priority</CardTitle>
            </CardHeader>
            <CardContent>
              <Select
                value={story.priority}
                onValueChange={(value) => handlePriorityChange(value as WorkItemPriority)}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="Low">Low</SelectItem>
                  <SelectItem value="Medium">Medium</SelectItem>
                  <SelectItem value="High">High</SelectItem>
                  <SelectItem value="Critical">Critical</SelectItem>
                </SelectContent>
              </Select>
            </CardContent>
          </Card>

          {/* Assignee */}
          {story.assigneeId && (
            <Card>
              <CardHeader className="pb-3">
                <CardTitle className="text-sm font-medium">Assignee</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-center gap-2">
                  <User className="h-4 w-4 text-muted-foreground" />
                  <span className="text-sm">{story.assigneeId}</span>
                </div>
              </CardContent>
            </Card>
          )}

          {/* Time Tracking */}
          {(story.estimatedHours !== undefined || story.actualHours !== undefined) && (
            <Card>
              <CardHeader className="pb-3">
                <CardTitle className="text-sm font-medium">Time Tracking</CardTitle>
              </CardHeader>
              <CardContent className="space-y-2">
                {story.estimatedHours !== undefined && (
                  <div className="flex items-center gap-2 text-sm">
                    <Clock className="h-4 w-4 text-muted-foreground" />
                    <span>Estimated: {story.estimatedHours}h</span>
                  </div>
                )}
                {story.actualHours !== undefined && (
                  <div className="flex items-center gap-2 text-sm">
                    <Clock className="h-4 w-4 text-muted-foreground" />
                    <span>Actual: {story.actualHours}h</span>
                  </div>
                )}
              </CardContent>
            </Card>
          )}

          {/* Dates */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm font-medium">Dates</CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
              <div className="flex items-start gap-2 text-sm">
                <Calendar className="h-4 w-4 text-muted-foreground mt-0.5" />
                <div className="flex-1">
                  <p className="font-medium">Created</p>
                  <p className="text-muted-foreground">
                    {formatDistanceToNow(new Date(story.createdAt), { addSuffix: true })}
                  </p>
                </div>
              </div>
              <div className="flex items-start gap-2 text-sm">
                <Calendar className="h-4 w-4 text-muted-foreground mt-0.5" />
                <div className="flex-1">
                  <p className="font-medium">Updated</p>
                  <p className="text-muted-foreground">
                    {formatDistanceToNow(new Date(story.updatedAt), { addSuffix: true })}
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Parent Epic Card */}
          {epic && (
            <Card className="hover:shadow-lg transition-shadow">
              <CardHeader className="pb-3">
                <CardTitle className="text-sm font-medium">Parent Epic</CardTitle>
              </CardHeader>
              <CardContent>
                <Link
                  href={`/epics/${epic.id}`}
                  className="block space-y-2 p-3 rounded-md border hover:bg-accent transition-colors"
                >
                  <div className="flex items-center gap-2">
                    <Layers className="h-4 w-4 text-muted-foreground" />
                    <span className="font-medium text-sm">{epic.name}</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge variant={getStatusColor(epic.status)} className="text-xs">
                      {epic.status}
                    </Badge>
                    <Badge className={`${getPriorityColor(epic.priority)} text-xs`}>
                      {epic.priority}
                    </Badge>
                  </div>
                </Link>
              </CardContent>
            </Card>
          )}
        </div>
      </div>

      {/* Edit Story Dialog */}
      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Edit Story</DialogTitle>
            <DialogDescription>Update the story details</DialogDescription>
          </DialogHeader>
          <StoryForm
            story={story}
            projectId={story.projectId}
            onSuccess={() => setIsEditDialogOpen(false)}
            onCancel={() => setIsEditDialogOpen(false)}
          />
        </DialogContent>
      </Dialog>

      {/* Delete Story Confirmation Dialog */}
      <AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Are you sure?</AlertDialogTitle>
            <AlertDialogDescription>
              This action cannot be undone. This will permanently delete the story
              and all its associated tasks.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDeleteStory}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              disabled={deleteStory.isPending}
            >
              {deleteStory.isPending ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Deleting...
                </>
              ) : (
                'Delete Story'
              )}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
