"use client";

import { useState, useEffect } from "react";
import { SubTask, PortfolioTask } from "./PortfolioLogs";
import { ScrollArea } from "@/app/shadcn_components/ui/scroll-area";
import { Card } from "@/app/shadcn_components/ui/card";
import { Button } from "@/app/shadcn_components/ui/button";
import { ChevronDown, AlertTriangle } from "lucide-react";
import { cn } from "@/lib/utils";

interface PortfolioSubtaskDetailsProps {
  subtasks: SubTask[];
  task?: PortfolioTask;
}

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.5 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>
  );
}

function formatJson(jsonString: string | null): string {
  if (!jsonString) return "N/A";
  try {
    return JSON.stringify(JSON.parse(jsonString), null, 2);
  } catch {
    return jsonString;
  }
}

function CopyableCodeBlock({ content, label }: { content: string; label: string }) {
  const [copied, setCopied] = useState(false);

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(content);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error("Failed to copy:", err);
    }
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-2">
        <p className="text-sm font-medium text-gray-900">{label}</p>
        <Button variant="ghost" size="sm" onClick={handleCopy} className="h-6 px-2 text-xs">
          {copied ? "✓ Copied" : "Copy"}
        </Button>
      </div>
      <pre className="bg-gray-50 p-3 rounded text-xs overflow-x-auto border border-gray-200 text-gray-700">
        {content}
      </pre>
    </div>
  );
}

function ExpandableSubtaskTile({
  subtask,
  index,
  isExpanded,
  onToggle,
}: {
  subtask: SubTask;
  index: number;
  isExpanded: boolean;
  onToggle: () => void;
}) {
  const isFailed = subtask.status.toLowerCase() === "failed";

  return (
    <Card className={`overflow-hidden ${isFailed ? "border-red-200" : ""}`}>
      <button
        onClick={onToggle}
        className="w-full p-4 flex items-center justify-between hover:bg-gray-50 transition-colors"
      >
        <div className="flex-1 text-left">
          <p className="text-sm font-semibold text-gray-900">Subtask {index + 1}</p>
          <code className="text-xs font-mono text-gray-600">{subtask.id}</code>
        </div>
        <div className="flex items-center gap-3">
          <StatusPill status={subtask.status} />
          <ChevronDown
            size={20}
            className={`text-gray-500 transition-transform ${isExpanded ? "rotate-180" : ""}`}
          />
        </div>
      </button>

      {isExpanded && (
        <div className="border-t border-gray-200 p-4 space-y-4 bg-gray-50">
          {/* Failure callout */}
          {isFailed && (
            <div className="flex items-start gap-2 p-3 rounded-lg bg-red-50 border border-red-200">
              <AlertTriangle className="h-4 w-4 text-red-500 mt-0.5 shrink-0" />
              <div>
                <p className="text-xs text-red-700 font-semibold">This subtask failed.</p>
                {subtask.cloudLogsURL && (
                  <a
                    href={subtask.cloudLogsURL}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-xs text-red-600 hover:text-red-800 underline mt-1 block"
                  >
                    View error logs →
                  </a>
                )}
              </div>
            </div>
          )}

          {/* Timeline */}
          {(subtask.jobStarted || subtask.jobCompleted) && (
            <div className="grid grid-cols-2 gap-3 text-sm">
              {subtask.jobStarted && (
                <div>
                  <p className="text-gray-600 text-xs font-medium">Started</p>
                  <p className="text-gray-900 text-xs">
                    {new Date(subtask.jobStarted).toLocaleString()}
                  </p>
                </div>
              )}
              {subtask.jobCompleted && (
                <div>
                  <p className="text-gray-600 text-xs font-medium">Completed</p>
                  <p className="text-gray-900 text-xs">
                    {new Date(subtask.jobCompleted).toLocaleString()}
                  </p>
                </div>
              )}
            </div>
          )}

          {/* Inputs */}
          {subtask.inputs && (
            <CopyableCodeBlock content={formatJson(subtask.inputs)} label="Inputs" />
          )}

          {/* Outputs */}
          {subtask.outputs && (
            <CopyableCodeBlock content={formatJson(subtask.outputs)} label="Outputs" />
          )}

          {/* Cloud Logs (for non-failed subtasks) */}
          {subtask.cloudLogsURL && !isFailed && (
            <div>
              <p className="text-sm font-medium text-gray-900 mb-2">Cloud Logs</p>
              <a
                href={subtask.cloudLogsURL}
                target="_blank"
                rel="noopener noreferrer"
                className="text-blue-600 hover:text-blue-800 text-xs break-all"
              >
                {subtask.cloudLogsURL}
              </a>
            </div>
          )}

          <p className="text-xs text-gray-500">
            Updated: {new Date(subtask.updatedAt).toLocaleString()}
          </p>
        </div>
      )}
    </Card>
  );
}

export default function PortfolioSubtaskDetails({
  subtasks,
  task,
}: PortfolioSubtaskDetailsProps) {
  const [expandedSubtasks, setExpandedSubtasks] = useState<Record<string, boolean>>({});

  useEffect(() => {
    setExpandedSubtasks({});
  }, [task?.id]);

  const toggleSubtask = (subtaskId: string) => {
    setExpandedSubtasks((prev) => ({ ...prev, [subtaskId]: !prev[subtaskId] }));
  };

  const total = Number(task?.totalSubtasks ?? 0);
  const completed = Number(task?.completedSubtasks ?? 0);
  const failed = Number(task?.failedSubtasks ?? 0);
  const completionPct = total > 0 ? Math.round((completed / total) * 100) : 0;
  const remainingCount = total - completed;
  const isAllDone = total > 0 && completed === total;

  return (
    <div className="flex flex-col h-full">
      {/* Task Header */}
      {task && (
        <div className="p-6 border-b border-gray-200 bg-white">
          <div className="space-y-3">
            <div className="flex items-start justify-between gap-3">
              <h2 className="text-base font-semibold text-gray-900 break-all">{task.taskSource}</h2>
              <StatusPill status={task.status} />
            </div>

            {/* Enriched stats */}
            {total > 0 && (
              <>
                <div className="w-full bg-gray-200 rounded-full h-2">
                  <div
                    className={cn(
                      "h-2 rounded-full transition-all",
                      isAllDone ? "bg-green-500" : failed > 0 ? "bg-red-500" : "bg-blue-500"
                    )}
                    style={{ width: `${completionPct}%` }}
                  />
                </div>
                <div className="flex items-center gap-3 text-sm">
                  <span className={isAllDone ? "text-green-600 font-medium" : "text-gray-600"}>
                    {completionPct}% complete
                  </span>
                  <span className="text-gray-400">·</span>
                  <span className="text-gray-600">{remainingCount} remaining</span>
                  {failed > 0 && (
                    <>
                      <span className="text-gray-400">·</span>
                      <span className="text-red-600 font-medium flex items-center gap-1">
                        <AlertTriangle className="h-3.5 w-3.5" />
                        {failed} failed
                      </span>
                    </>
                  )}
                </div>
              </>
            )}

            <div className="grid grid-cols-2 gap-4 text-sm">
              <div>
                <p className="text-gray-600">Task ID</p>
                <code className="text-xs font-mono text-gray-900 break-all">{task.id}</code>
              </div>
              {task.service && (
                <div>
                  <p className="text-gray-600">Service</p>
                  <p className="text-gray-900">{task.service}</p>
                </div>
              )}
              {task.jobStarted && (
                <div>
                  <p className="text-gray-600">Job Started</p>
                  <p className="text-gray-900 text-xs">
                    {new Date(task.jobStarted).toLocaleString()}
                  </p>
                </div>
              )}
              {task.jobCompleted && (
                <div>
                  <p className="text-gray-600">Job Completed</p>
                  <p className="text-gray-900 text-xs">
                    {new Date(task.jobCompleted).toLocaleString()}
                  </p>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Subtasks List */}
      <ScrollArea key={task?.id} className="flex-1 p-6">
        <div className="space-y-4">
          <h3 className="text-base font-semibold text-gray-900">
            Subtasks ({subtasks.length})
          </h3>

          {subtasks.length === 0 && (
            <div className="text-center py-8 text-gray-500 text-sm">No subtasks found</div>
          )}

          <div className="space-y-3">
            {subtasks.map((subtask, index) => (
              <ExpandableSubtaskTile
                key={subtask.id}
                subtask={subtask}
                index={index}
                isExpanded={expandedSubtasks[subtask.id] || false}
                onToggle={() => toggleSubtask(subtask.id)}
              />
            ))}
          </div>
        </div>
      </ScrollArea>
    </div>
  );
}
