'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeft, Archive, Pencil } from 'lucide-react';
import { toast } from 'sonner';

import { tasksApi } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';

export function TaskDetailClient() {
  const params = useParams();
  const router = useRouter();
  const queryClient = useQueryClient();
  const taskId = Number(params.id);

  const { data: task, isLoading, error } = useQuery({
    queryKey: ['task', taskId],
    queryFn: () => tasksApi.get(taskId),
    enabled: !!taskId,
  });

  const deleteMutation = useMutation({
    mutationFn: () => tasksApi.delete(taskId),
    onSuccess: () => {
      toast.success('Task archived successfully');
      queryClient.invalidateQueries({ queryKey: ['tasks'] });
      router.push('/tasks');
    },
    onError: () => {
      toast.error('Failed to archive task');
    },
  });

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-muted-foreground">Loading...</div>
      </div>
    );
  }

  if (error || !task) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-red-500">Failed to load task</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" asChild>
            <Link href="/tasks">
              <ArrowLeft className="h-4 w-4" />
            </Link>
          </Button>
          <div>
            <h1 className="text-2xl font-bold">{task.title}</h1>
            <p className="text-muted-foreground">{task.residence_name}</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" asChild>
            <Link href={`/tasks/${taskId}/edit`}>
              <Pencil className="mr-2 h-4 w-4" />
              Edit
            </Link>
          </Button>
          <Button
            variant="destructive"
            onClick={() => {
              if (confirm('Are you sure you want to archive this task?')) {
                deleteMutation.mutate();
              }
            }}
            disabled={deleteMutation.isPending}
          >
            <Archive className="mr-2 h-4 w-4" />
            Archive
          </Button>
        </div>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        {/* Task Details */}
        <Card>
          <CardHeader>
            <CardTitle>Task Details</CardTitle>
            <CardDescription>Basic task information</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <div className="text-sm font-medium text-muted-foreground">Description</div>
              <div className="whitespace-pre-wrap">{task.description || '-'}</div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <div className="text-sm font-medium text-muted-foreground">Category</div>
                <div>{task.category_name || '-'}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Priority</div>
                <div>{task.priority_name || '-'}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">In Progress</div>
                <div>{task.in_progress ? 'Yes' : 'No'}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Due Date</div>
                <div>{task.due_date ? new Date(task.due_date).toLocaleDateString() : '-'}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Next Due Date</div>
                <div>{task.next_due_date ? new Date(task.next_due_date).toLocaleDateString() : '-'}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Frequency</div>
                <div>{task.frequency_name || '-'}</div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Status & Costs */}
        <Card>
          <CardHeader>
            <CardTitle>Status & Costs</CardTitle>
            <CardDescription>Task state and financial info</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <div className="text-sm font-medium text-muted-foreground">State</div>
                <div className="flex gap-2">
                  {task.is_cancelled && <Badge variant="destructive">Cancelled</Badge>}
                  {task.is_archived && <Badge variant="secondary">Archived</Badge>}
                  {!task.is_cancelled && !task.is_archived && <Badge variant="default">Active</Badge>}
                </div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Completions</div>
                <div className="text-2xl font-bold">{task.completion_count}</div>
              </div>
            </div>

            <Separator />

            <div className="grid grid-cols-2 gap-4">
              <div>
                <div className="text-sm font-medium text-muted-foreground">Estimated Cost</div>
                <div>{task.estimated_cost ? `$${task.estimated_cost.toFixed(2)}` : '-'}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Created</div>
                <div>{new Date(task.created_at).toLocaleDateString()}</div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* People */}
        <Card className="md:col-span-2">
          <CardHeader>
            <CardTitle>People</CardTitle>
            <CardDescription>Users associated with this task</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <div className="text-sm font-medium text-muted-foreground">Created By</div>
                <div>{task.created_by_name}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Assigned To</div>
                {task.assigned_to ? (
                  <Link
                    href={`/users/${task.assigned_to.id}`}
                    className="text-blue-600 hover:underline"
                  >
                    {task.assigned_to.username}
                  </Link>
                ) : (
                  <div>-</div>
                )}
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
