"use client";

import { use } from "react";
import Image from "next/image";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { PageHeader } from "@/components/shared/page-header";
import { LoadingSkeleton } from "@/components/shared/loading-skeleton";
import { ErrorBanner } from "@/components/shared/error-banner";
import { StarRating } from "@/components/shared/star-rating";
import { TaskActionsMenu } from "@/components/tasks/task-actions-menu";
import { useTask, useTaskCompletions } from "@/lib/hooks/use-tasks";
import {
  Calendar,
  DollarSign,
  Repeat,
  User,
  Wrench,
  Home,
} from "lucide-react";

export default function TaskDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = use(params);
  const taskId = Number(id);
  const { data: task, isLoading, isError, error, refetch } = useTask(taskId);
  const { data: completions } = useTaskCompletions(taskId);

  if (isLoading) {
    return <LoadingSkeleton variant="detail" />;
  }

  if (isError) {
    return (
      <ErrorBanner
        message={error instanceof Error ? error.message : "Failed to load task"}
        onRetry={() => refetch()}
      />
    );
  }

  if (!task) return null;

  const statusLabel = task.is_cancelled
    ? "Cancelled"
    : task.is_archived
      ? "Archived"
      : task.in_progress
        ? "In Progress"
        : "Active";

  const statusVariant = task.is_cancelled
    ? "destructive"
    : task.is_archived
      ? "secondary"
      : task.in_progress
        ? "default"
        : "outline";

  return (
    <div className="space-y-6">
      <PageHeader title={task.title}>
        <TaskActionsMenu taskId={task.id} />
      </PageHeader>

      {/* Status & badges */}
      <div className="flex flex-wrap gap-2">
        <Badge variant={statusVariant}>{statusLabel}</Badge>
        {task.priority && (
          <Badge variant="outline">
            {task.priority.icon && <span className="mr-1">{task.priority.icon}</span>}
            {task.priority.name}
          </Badge>
        )}
        {task.category && (
          <Badge variant="secondary">
            {task.category.icon && <span className="mr-1">{task.category.icon}</span>}
            {task.category.name}
          </Badge>
        )}
        {task.frequency && (
          <Badge variant="outline">
            <Repeat className="size-3 mr-1" />
            {task.frequency.name}
          </Badge>
        )}
      </div>

      {/* Metadata */}
      <Card>
        <CardHeader>
          <CardTitle>Details</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm">
            <div className="flex items-center gap-2">
              <Home className="size-4 text-muted-foreground shrink-0" />
              <span className="text-muted-foreground">Residence:</span>
              <span>{task.residence_name}</span>
            </div>

            {task.due_date && (
              <div className="flex items-center gap-2">
                <Calendar className="size-4 text-muted-foreground shrink-0" />
                <span className="text-muted-foreground">Due Date:</span>
                <span>{new Date(task.due_date).toLocaleDateString()}</span>
              </div>
            )}

            {task.next_due_date && (
              <div className="flex items-center gap-2">
                <Calendar className="size-4 text-muted-foreground shrink-0" />
                <span className="text-muted-foreground">Next Due:</span>
                <span>
                  {new Date(task.next_due_date).toLocaleDateString()}
                </span>
              </div>
            )}

            {task.estimated_cost != null && task.estimated_cost > 0 && (
              <div className="flex items-center gap-2">
                <DollarSign className="size-4 text-muted-foreground shrink-0" />
                <span className="text-muted-foreground">Estimated Cost:</span>
                <span>${task.estimated_cost.toFixed(2)}</span>
              </div>
            )}

            {task.actual_cost != null && task.actual_cost > 0 && (
              <div className="flex items-center gap-2">
                <DollarSign className="size-4 text-muted-foreground shrink-0" />
                <span className="text-muted-foreground">Actual Cost:</span>
                <span>${task.actual_cost.toFixed(2)}</span>
              </div>
            )}

            {task.contractor && (
              <div className="flex items-center gap-2">
                <Wrench className="size-4 text-muted-foreground shrink-0" />
                <span className="text-muted-foreground">Contractor:</span>
                <span>
                  {task.contractor.name}
                  {task.contractor.company && ` (${task.contractor.company})`}
                </span>
              </div>
            )}

            {task.assigned_to && (
              <div className="flex items-center gap-2">
                <User className="size-4 text-muted-foreground shrink-0" />
                <span className="text-muted-foreground">Assigned To:</span>
                <span>
                  {task.assigned_to.first_name} {task.assigned_to.last_name}
                </span>
              </div>
            )}

            <div className="flex items-center gap-2">
              <span className="text-muted-foreground">Completions:</span>
              <span>{task.completion_count}</span>
            </div>

            {task.last_completed_at && (
              <div className="flex items-center gap-2">
                <span className="text-muted-foreground">Last Completed:</span>
                <span>
                  {new Date(task.last_completed_at).toLocaleDateString()}
                </span>
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Description */}
      {task.description && (
        <Card>
          <CardHeader>
            <CardTitle>Description</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-sm whitespace-pre-wrap">{task.description}</p>
          </CardContent>
        </Card>
      )}

      {/* Completion history */}
      {completions && completions.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Completion History</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {completions.map((completion) => (
                <div
                  key={completion.id}
                  className="border rounded-lg p-3 space-y-2"
                >
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium">
                      {new Date(completion.completed_at).toLocaleDateString()}{" "}
                      {new Date(completion.completed_at).toLocaleTimeString()}
                    </span>
                    {completion.rating != null && completion.rating > 0 && (
                      <StarRating
                        value={completion.rating}
                        readonly
                        size="sm"
                      />
                    )}
                  </div>

                  {completion.completed_by && (
                    <p className="text-xs text-muted-foreground">
                      Completed by {completion.completed_by.first_name}{" "}
                      {completion.completed_by.last_name}
                    </p>
                  )}

                  {completion.notes && (
                    <p className="text-sm">{completion.notes}</p>
                  )}

                  {completion.actual_cost != null &&
                    completion.actual_cost > 0 && (
                      <p className="text-sm text-muted-foreground">
                        Cost: ${completion.actual_cost.toFixed(2)}
                      </p>
                    )}

                  {completion.images.length > 0 && (
                    <div className="flex gap-2 flex-wrap">
                      {completion.images.map((img) => (
                        <Image
                          key={img.id}
                          src={img.image_url}
                          alt={img.caption || "Completion photo"}
                          width={80}
                          height={80}
                          className="size-20 rounded-md object-cover border"
                        />
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
