"use client";

import { useState, useMemo } from "react";
import { PortfolioTask } from "./PortfolioLogs";
import { cn } from "@/lib/utils";
import { Button } from "@/app/shadcn_components/ui/button";
import { Input } from "@/app/shadcn_components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/app/shadcn_components/ui/select";

interface PortfolioTaskListProps {
  tasks: PortfolioTask[];
  selectedTaskId: string | null;
  onSelectTask: (taskId: string) => void;
  loading: boolean;
  loadingMore: boolean;
  error: string | null;
  total: number;
  onLoadMore: () => void;
  onRefresh: () => void;
}

type SortOption = "recent" | "oldest" | "status" | "service";

function StatusPill({ status }: { status: string }) {
  const s = status.toLowerCase();
  const isComplete = s === "completed" || s === "complete";
  const isInProgress = s === "in progress";
  const isFailed = s === "failed" || s === "failure" || s === "error";

  return (
    <span
      className={cn(
        "inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium",
        isComplete && "bg-green-100 text-green-700",
        isInProgress && "bg-blue-100 text-blue-700",
        isFailed && "bg-red-100 text-red-700",
        !isComplete &&
          !isInProgress &&
          !isFailed &&
          "bg-gray-100 text-gray-600",
      )}
    >
      {status}
    </span>
  );
}

export default function PortfolioTaskList({
  tasks,
  selectedTaskId,
  onSelectTask,
  loading,
  loadingMore,
  error,
  total,
  onLoadMore,
  onRefresh,
}: PortfolioTaskListProps) {
  const [searchQuery, setSearchQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [serviceFilter, setServiceFilter] = useState<string>("all");
  const [sortBy, setSortBy] = useState<SortOption>("recent");

  const uniqueStatuses = useMemo(
    () => Array.from(new Set(tasks.map((t) => t.status))).sort(),
    [tasks],
  );
  const uniqueServices = useMemo(
    () =>
      Array.from(
        new Set(tasks.map((t) => t.service).filter(Boolean)),
      ).sort() as string[],
    [tasks],
  );

  const filteredTasks = useMemo(() => {
    let result = tasks;

    if (statusFilter !== "all") {
      result = result.filter((t) => t.status === statusFilter);
    }
    if (serviceFilter !== "all") {
      result = result.filter((t) => t.service === serviceFilter);
    }
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      result = result.filter(
        (t) =>
          t.id.toLowerCase().includes(query) ||
          t.taskSource.toLowerCase().includes(query) ||
          (t.service?.toLowerCase().includes(query) ?? false),
      );
    }

    const sorted = [...result];
    switch (sortBy) {
      case "recent":
        sorted.sort(
          (a, b) =>
            new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime(),
        );
        break;
      case "oldest":
        sorted.sort(
          (a, b) =>
            new Date(a.updatedAt).getTime() - new Date(b.updatedAt).getTime(),
        );
        break;
      case "status":
        sorted.sort((a, b) => a.status.localeCompare(b.status));
        break;
      case "service":
        sorted.sort((a, b) => (a.service ?? "").localeCompare(b.service ?? ""));
        break;
    }

    return sorted;
  }, [tasks, statusFilter, serviceFilter, searchQuery, sortBy]);

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="p-4 border-b border-gray-200 space-y-2">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-base font-semibold text-gray-900">Tasks</h2>
            <p className="text-xs text-gray-600">
              {filteredTasks.length} of {tasks.length} (Total: {total})
            </p>
          </div>
          <Button
            variant="outline"
            size="sm"
            onClick={onRefresh}
            disabled={loading}
            className="text-xs"
          >
            ↻ Refresh
          </Button>
        </div>
      </div>

      {/* Filters */}
      <div className="p-3 border-b border-gray-200 space-y-2 bg-gray-50">
        <Input
          placeholder="Search by ID, source, or service..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          className="text-xs h-8"
        />
        <Select
          value={sortBy}
          onValueChange={(value) => setSortBy(value as SortOption)}
        >
          <SelectTrigger className="text-xs h-8">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="recent">Most Recent</SelectItem>
            <SelectItem value="oldest">Oldest First</SelectItem>
            <SelectItem value="status">By Status</SelectItem>
            <SelectItem value="service">By Service</SelectItem>
          </SelectContent>
        </Select>
        {uniqueStatuses.length > 0 && (
          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger className="text-xs h-8">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Statuses</SelectItem>
              {uniqueStatuses.map((status) => (
                <SelectItem key={status} value={status}>
                  {status}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        )}
        {uniqueServices.length > 0 && (
          <Select value={serviceFilter} onValueChange={setServiceFilter}>
            <SelectTrigger className="text-xs h-8">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Services</SelectItem>
              {uniqueServices.map((service) => (
                <SelectItem key={service} value={service}>
                  {service}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        )}
        {(searchQuery || statusFilter !== "all" || serviceFilter !== "all") && (
          <Button
            variant="outline"
            size="sm"
            onClick={() => {
              setSearchQuery("");
              setStatusFilter("all");
              setServiceFilter("all");
            }}
            className="w-full text-xs h-7"
          >
            Clear Filters
          </Button>
        )}
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto">
        {error && (
          <div className="p-4 m-4 bg-red-50 border border-red-200 rounded text-red-700 text-xs">
            {error}
          </div>
        )}
        {loading && (
          <div className="p-4 text-center text-gray-500 text-sm">
            Loading tasks...
          </div>
        )}
        {!loading && !error && tasks.length === 0 && (
          <div className="p-4 text-center text-gray-500 text-sm">
            No tasks found for this portfolio
          </div>
        )}

        <div className="divide-y divide-gray-200 pb-4">
          {filteredTasks.map((task) => {
            const total = Number(task.totalSubtasks);
            const completed = Number(task.completedSubtasks);
            const failed = Number(task.failedSubtasks);
            const completionPct =
              total > 0 ? Math.round((completed / total) * 100) : 0;
            const remainingCount = total - completed;
            const isAllDone = total > 0 && completed === total;

            return (
              <button
                key={task.id}
                onClick={() => onSelectTask(task.id)}
                className={cn(
                  "w-full min-w-0 overflow-hidden text-left p-4 transition-colors hover:bg-gray-50",
                  selectedTaskId === task.id
                    ? "bg-blue-50 border-l-4 border-blue-500"
                    : "border-l-4 border-transparent",
                )}
              >
                <div className="space-y-1.5 min-w-0 pr-2">
                  {/* Status badge at top */}
                  <StatusPill status={task.status} />

                  {/* Route name — truncated with full text on hover */}
                  <p
                    className="font-medium text-gray-900 text-sm truncate"
                    title={task.taskSource}
                  >
                    {task.taskSource}
                  </p>

                  {task.service && (
                    <p
                      className="text-xs text-gray-500 truncate"
                      title={task.service}
                    >
                      {task.service}
                    </p>
                  )}

                  {/* Completion progress */}
                  {total > 0 && (
                    <>
                      <div className="bg-gray-200 rounded-full h-1.5">
                        <div
                          className={cn(
                            "h-1.5 rounded-full transition-all",
                            isAllDone
                              ? "bg-green-500"
                              : failed > 0
                                ? "bg-red-500"
                                : "bg-blue-500",
                          )}
                          style={{ width: `${completionPct}%` }}
                        />
                      </div>
                      <p
                        className={cn(
                          "text-xs",
                          isAllDone
                            ? "text-green-600 font-medium"
                            : "text-gray-500",
                        )}
                      >
                        {completionPct}% complete &middot; {remainingCount}{" "}
                        remaining
                      </p>
                    </>
                  )}

                  {/* Failure indicator */}
                  {failed > 0 && (
                    <p className="text-xs text-red-600 font-medium">
                      {failed} failed subtask{failed > 1 ? "s" : ""}
                    </p>
                  )}

                  <p className="text-xs text-gray-400">
                    {new Date(task.updatedAt).toLocaleString()}
                  </p>
                </div>
              </button>
            );
          })}

          {tasks.length < total && (
            <div className="p-4 flex justify-center border-t border-gray-200">
              <Button
                variant="outline"
                size="sm"
                onClick={onLoadMore}
                disabled={loadingMore}
                className="text-xs"
              >
                {loadingMore ? "Loading..." : "Load More"}
              </Button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
