"use client";

import { useEffect, useState, useCallback } from "react";
import { getWorkflowExecutions, getWorkflowExecution, WorkflowExecution } from "@/lib/api";
import { RefreshCw, Play, CheckCircle, XCircle, Clock, ChevronDown, Activity } from "lucide-react";

interface WorkflowExecutionsProps {
  workflowId?: string;
}

export function WorkflowExecutions({ workflowId }: WorkflowExecutionsProps) {
  const [executions, setExecutions] = useState<WorkflowExecution[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [expandedDetail, setExpandedDetail] = useState<WorkflowExecution | null>(null);

  const loadExecutions = useCallback(() => {
    setLoading(true);
    setError("");
    getWorkflowExecutions(workflowId)
      .then((data) => setExecutions(Array.isArray(data) ? data : []))
      .catch((err) => {
        console.error("Failed to load workflow executions:", err);
        setError("Failed to load executions");
      })
      .finally(() => setLoading(false));
  }, [workflowId]);

  useEffect(() => {
    loadExecutions();
  }, [loadExecutions]);

  const handleExpand = (execution: WorkflowExecution) => {
    if (expandedId === execution.id) {
      setExpandedId(null);
      setExpandedDetail(null);
      return;
    }
    setExpandedId(execution.id);
    if (!execution.steps || execution.steps.length === 0) {
      getWorkflowExecution(execution.id)
        .then((detail) => setExpandedDetail(detail))
        .catch((err) => console.error("Failed to load execution detail:", err));
    } else {
      setExpandedDetail(execution);
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case "completed":
        return <CheckCircle size={14} className="text-slack-green" />;
      case "failed":
        return <XCircle size={14} className="text-slack-red" />;
      case "running":
        return <Play size={14} className="text-slack-blue animate-pulse" />;
      case "cancelled":
        return <XCircle size={14} className="text-gray-400" />;
      default:
        return <Clock size={14} className="text-gray-400" />;
    }
  };

  const formatDuration = (ms?: number) => {
    if (!ms) return "—";
    if (ms < 1000) return `${ms}ms`;
    return `${(ms / 1000).toFixed(1)}s`;
  };

  const formatTime = (dateStr?: string) => {
    if (!dateStr) return "—";
    try {
      return new Date(dateStr).toLocaleString("en-US", {
        month: "short",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit",
      });
    } catch {
      return dateStr;
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center text-gray-400 py-12">
        <RefreshCw size={20} className="animate-pulse" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center text-slack-red py-12 text-sm">
        {error}
        <button onClick={loadExecutions} className="ml-2 text-slack-purple hover:underline">
          Retry
        </button>
      </div>
    );
  }

  if (executions.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center py-16 text-gray-400">
        <Activity size={48} className="mb-3 opacity-50" />
        <p className="text-sm">No executions found.</p>
        <p className="text-xs mt-1">Workflow executions will appear here.</p>
      </div>
    );
  }

  return (
    <div className="space-y-2">
      {executions.map((exec) => {
        const isExpanded = expandedId === exec.id;
        const detail = isExpanded ? expandedDetail : null;
        return (
          <div
            key={exec.id}
            className="rounded-lg border border-gray-200 bg-white shadow-sm overflow-hidden"
          >
            <button
              onClick={() => handleExpand(exec)}
              className="w-full flex items-center justify-between p-4 hover:bg-gray-50 transition-colors"
            >
              <div className="flex items-center gap-3 flex-1 min-w-0 text-left">
                {getStatusIcon(exec.status)}
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium text-gray-800 truncate">
                    {exec.workflow_name || `Workflow ${exec.workflow_id.substring(0, 8)}`}
                  </p>
                  <div className="flex items-center gap-3 text-xs text-gray-400 mt-0.5">
                    <span className="capitalize">{exec.status}</span>
                    <span>Started: {formatTime(exec.started_at)}</span>
                    {exec.duration_ms !== undefined && (
                      <span>Duration: {formatDuration(exec.duration_ms)}</span>
                    )}
                    {exec.trigger && <span>Trigger: {exec.trigger}</span>}
                  </div>
                </div>
              </div>
              <ChevronDown
                size={16}
                className={`text-gray-400 transition-transform ${isExpanded ? "rotate-180" : ""}`}
              />
            </button>

            {/* Expanded detail */}
            {isExpanded && detail && (
              <div className="border-t border-gray-100 p-4 bg-gray-50">
                {detail.error && (
                  <div className="mb-3 p-2 rounded-md bg-slack-red/5 border border-slack-red/20">
                    <p className="text-xs text-slack-red font-medium">Error:</p>
                    <p className="text-xs text-slack-red mt-1">{detail.error}</p>
                  </div>
                )}
                {detail.steps && detail.steps.length > 0 ? (
                  <div>
                    <p className="text-xs font-semibold text-gray-500 uppercase mb-2">Steps</p>
                    <div className="space-y-2">
                      {detail.steps.map((step, idx) => (
                        <div
                          key={step.step_id || idx}
                          className="flex items-start gap-2 p-2 rounded-md bg-white border border-gray-200"
                        >
                          {getStatusIcon(step.status)}
                          <div className="flex-1 min-w-0">
                            <p className="text-sm font-medium text-gray-800">{step.name}</p>
                            <p className="text-xs text-gray-400 capitalize">{step.status}</p>
                            {step.output && (
                              <p className="text-xs text-gray-500 mt-1 font-mono bg-gray-50 p-1 rounded">
                                {step.output}
                              </p>
                            )}
                            {step.error && (
                              <p className="text-xs text-slack-red mt-1">{step.error}</p>
                            )}
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                ) : (
                  <p className="text-xs text-gray-400">No step details available.</p>
                )}
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

export default WorkflowExecutions;