"use client";

import { useState, useEffect, useCallback } from "react";
import {
  RefreshCw,
  Play,
  Pause,
  XCircle,
  CheckCircle2,
  AlertTriangle,
  Clock,
  Activity,
  Search,
  Filter,
  ChevronDown,
  ChevronRight,
  Eye,
  Ban,
  Send,
  History,
  Loader2,
  Server,
  ServerOff,
  Zap,
  Calendar,
  CreditCard,
  Database,
  Mail,
} from "lucide-react";

interface Workflow {
  workflowId: string;
  runId: string;
  type: string;
  status: string;
  startTime: string | null;
  closeTime: string | null;
  executionTime: string | null;
  taskQueue: string;
  memo?: Record<string, unknown>;
  searchAttributes?: Record<string, unknown>;
}

interface WorkflowStats {
  running: number;
  completed: number;
  failed: number;
  cancelled: number;
  total: number;
}

interface WorkflowResponse {
  workflows: Workflow[];
  stats: WorkflowStats;
  temporalConnected: boolean;
  message?: string;
}

const WORKFLOW_TYPES = [
  { value: "all", label: "All Types" },
  { value: "BookingWorkflow", label: "Bookings", icon: Calendar },
  { value: "PaymentWorkflow", label: "Payments", icon: CreditCard },
  { value: "DualDatabaseSyncWorkflow", label: "Database Sync", icon: Database },
  { value: "OnboardingEmailSequence", label: "Onboarding Emails", icon: Mail },
];

const STATUS_FILTERS = [
  { value: "all", label: "All Statuses" },
  { value: "running", label: "Running", color: "text-blue-600 bg-blue-50" },
  {
    value: "completed",
    label: "Completed",
    color: "text-green-600 bg-green-50",
  },
  { value: "failed", label: "Failed", color: "text-red-600 bg-red-50" },
  { value: "cancelled", label: "Cancelled", color: "text-gray-600 bg-gray-50" },
];

export default function TemporalDashboard() {
  const [workflows, setWorkflows] = useState<Workflow[]>([]);
  const [stats, setStats] = useState<WorkflowStats>({
    running: 0,
    completed: 0,
    failed: 0,
    cancelled: 0,
    total: 0,
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [temporalConnected, setTemporalConnected] = useState(false);
  const [message, setMessage] = useState<string | null>(null);

  // Filters
  const [statusFilter, setStatusFilter] = useState("all");
  const [typeFilter, setTypeFilter] = useState("all");
  const [searchQuery, setSearchQuery] = useState("");

  // Selected workflow for details
  const [selectedWorkflow, setSelectedWorkflow] = useState<Workflow | null>(
    null,
  );
  const [workflowDetails, setWorkflowDetails] = useState<any>(null);
  const [loadingDetails, setLoadingDetails] = useState(false);

  // Action states
  const [actionLoading, setActionLoading] = useState<string | null>(null);

  const fetchWorkflows = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      const params = new URLSearchParams();
      if (statusFilter !== "all") params.set("status", statusFilter);
      if (typeFilter !== "all") params.set("type", typeFilter);

      const response = await fetch(`/api/staff/workflows?${params}`);
      const data: WorkflowResponse = await response.json();

      if (!response.ok) {
        throw new Error(data.message || "Failed to fetch workflows");
      }

      setWorkflows(data.workflows);
      setStats(data.stats);
      setTemporalConnected(data.temporalConnected);
      setMessage(data.message || null);
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred");
    } finally {
      setLoading(false);
    }
  }, [statusFilter, typeFilter]);

  useEffect(() => {
    fetchWorkflows();
    // Auto-refresh every 30 seconds
    const interval = setInterval(fetchWorkflows, 30000);
    return () => clearInterval(interval);
  }, [fetchWorkflows]);

  const handleWorkflowAction = async (
    workflowId: string,
    action: "cancel" | "terminate" | "describe" | "history",
    data?: any,
  ) => {
    try {
      setActionLoading(`${workflowId}-${action}`);

      const response = await fetch("/api/staff/workflows", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ workflowId, action, ...data }),
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || "Action failed");
      }

      if (action === "describe") {
        setWorkflowDetails(result);
      } else if (action === "history") {
        setWorkflowDetails({ ...workflowDetails, history: result.events });
      } else {
        // Refresh workflows after action
        await fetchWorkflows();
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Action failed");
    } finally {
      setActionLoading(null);
    }
  };

  const handleViewDetails = async (workflow: Workflow) => {
    setSelectedWorkflow(workflow);
    setLoadingDetails(true);
    await handleWorkflowAction(workflow.workflowId, "describe");
    setLoadingDetails(false);
  };

  const filteredWorkflows = workflows.filter((workflow) => {
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      return (
        workflow.workflowId.toLowerCase().includes(query) ||
        workflow.type.toLowerCase().includes(query) ||
        workflow.taskQueue.toLowerCase().includes(query)
      );
    }
    return true;
  });

  const getStatusBadge = (status: string) => {
    const statusConfig: Record<string, { color: string; icon: any }> = {
      RUNNING: { color: "text-blue-700 bg-blue-100", icon: Play },
      COMPLETED: { color: "text-green-700 bg-green-100", icon: CheckCircle2 },
      FAILED: { color: "text-red-700 bg-red-100", icon: AlertTriangle },
      CANCELED: { color: "text-gray-700 bg-gray-100", icon: XCircle },
      TERMINATED: { color: "text-orange-700 bg-orange-100", icon: Ban },
      TIMED_OUT: { color: "text-amber-700 bg-amber-100", icon: Clock },
    };

    const config = statusConfig[status] || {
      color: "text-gray-700 bg-gray-100",
      icon: Activity,
    };
    const Icon = config.icon;

    return (
      <span
        className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium ${config.color}`}
      >
        <Icon className="w-3.5 h-3.5" />
        {status}
      </span>
    );
  };

  const getWorkflowTypeIcon = (type: string) => {
    const typeConfig = WORKFLOW_TYPES.find((t) => t.value === type);
    if (typeConfig?.icon) {
      const Icon = typeConfig.icon;
      return <Icon className="w-4 h-4 text-gray-500" />;
    }
    return <Zap className="w-4 h-4 text-gray-500" />;
  };

  const formatTime = (time: string | null) => {
    if (!time) return "-";
    return new Date(time).toLocaleString();
  };

  const formatDuration = (start: string | null, end: string | null) => {
    if (!start) return "-";
    const startTime = new Date(start).getTime();
    const endTime = end ? new Date(end).getTime() : Date.now();
    const diff = endTime - startTime;

    if (diff < 1000) return `${diff}ms`;
    if (diff < 60000) return `${Math.round(diff / 1000)}s`;
    if (diff < 3600000) return `${Math.round(diff / 60000)}m`;
    return `${Math.round(diff / 3600000)}h`;
  };

  return (
    <div className="space-y-6">
      {/* Connection Status */}
      {!temporalConnected && (
        <div className="bg-amber-50 border border-amber-200 rounded-xl p-4 flex items-start gap-3">
          <ServerOff className="w-5 h-5 text-amber-600 mt-0.5" />
          <div>
            <h3 className="text-sm font-semibold text-amber-800">
              Temporal Server Not Connected
            </h3>
            <p className="text-sm text-amber-700 mt-1">
              {message ||
                "Start Temporal with: docker-compose -f docker-compose.temporal.yml up -d"}
            </p>
          </div>
        </div>
      )}

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
        <div className="bg-white rounded-xl border border-gray-200 p-5 hover:shadow-md transition-shadow">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-500">
                Total Workflows
              </p>
              <p className="text-2xl font-bold text-gray-900 mt-1">
                {stats.total}
              </p>
            </div>
            <div className="w-12 h-12 rounded-xl bg-gray-100 flex items-center justify-center">
              <Activity className="w-6 h-6 text-gray-600" />
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl border border-gray-200 p-5 hover:shadow-md transition-shadow">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-500">Running</p>
              <p className="text-2xl font-bold text-blue-600 mt-1">
                {stats.running}
              </p>
            </div>
            <div className="w-12 h-12 rounded-xl bg-blue-100 flex items-center justify-center">
              <Play className="w-6 h-6 text-blue-600" />
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl border border-gray-200 p-5 hover:shadow-md transition-shadow">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-500">Completed</p>
              <p className="text-2xl font-bold text-green-600 mt-1">
                {stats.completed}
              </p>
            </div>
            <div className="w-12 h-12 rounded-xl bg-green-100 flex items-center justify-center">
              <CheckCircle2 className="w-6 h-6 text-green-600" />
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl border border-gray-200 p-5 hover:shadow-md transition-shadow">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-500">Failed</p>
              <p className="text-2xl font-bold text-red-600 mt-1">
                {stats.failed}
              </p>
            </div>
            <div className="w-12 h-12 rounded-xl bg-red-100 flex items-center justify-center">
              <AlertTriangle className="w-6 h-6 text-red-600" />
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl border border-gray-200 p-5 hover:shadow-md transition-shadow">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-500">Cancelled</p>
              <p className="text-2xl font-bold text-gray-600 mt-1">
                {stats.cancelled}
              </p>
            </div>
            <div className="w-12 h-12 rounded-xl bg-gray-100 flex items-center justify-center">
              <XCircle className="w-6 h-6 text-gray-600" />
            </div>
          </div>
        </div>
      </div>

      {/* Workflows Table */}
      <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
        {/* Header */}
        <div className="p-4 border-b border-gray-100 flex flex-col md:flex-row md:items-center justify-between gap-4">
          <h2 className="text-lg font-semibold text-gray-900">Workflows</h2>

          <div className="flex flex-wrap items-center gap-3">
            {/* Search */}
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                type="text"
                placeholder="Search workflows..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-9 pr-4 py-2 text-sm border border-gray-200 rounded-lg focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 outline-none w-64"
              />
            </div>

            {/* Type Filter */}
            <select
              value={typeFilter}
              onChange={(e) => setTypeFilter(e.target.value)}
              className="px-3 py-2 text-sm border border-gray-200 rounded-lg focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 outline-none"
            >
              {WORKFLOW_TYPES.map((type) => (
                <option key={type.value} value={type.value}>
                  {type.label}
                </option>
              ))}
            </select>

            {/* Status Filter */}
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="px-3 py-2 text-sm border border-gray-200 rounded-lg focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 outline-none"
            >
              {STATUS_FILTERS.map((status) => (
                <option key={status.value} value={status.value}>
                  {status.label}
                </option>
              ))}
            </select>

            {/* Refresh Button */}
            <button
              onClick={fetchWorkflows}
              disabled={loading}
              className="inline-flex items-center gap-2 px-3 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50"
            >
              <RefreshCw
                className={`w-4 h-4 ${loading ? "animate-spin" : ""}`}
              />
              Refresh
            </button>
          </div>
        </div>

        {/* Error Message */}
        {error && (
          <div className="p-4 bg-red-50 border-b border-red-100">
            <p className="text-sm text-red-700">{error}</p>
          </div>
        )}

        {/* Table */}
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                  Workflow
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                  Type
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                  Status
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                  Task Queue
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                  Started
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                  Duration
                </th>
                <th className="px-4 py-3 text-right text-xs font-semibold text-gray-600 uppercase tracking-wider">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {loading && filteredWorkflows.length === 0 ? (
                <tr>
                  <td colSpan={7} className="px-4 py-12 text-center">
                    <Loader2 className="w-8 h-8 text-gray-400 animate-spin mx-auto" />
                    <p className="text-sm text-gray-500 mt-2">
                      Loading workflows...
                    </p>
                  </td>
                </tr>
              ) : filteredWorkflows.length === 0 ? (
                <tr>
                  <td colSpan={7} className="px-4 py-12 text-center">
                    <Activity className="w-12 h-12 text-gray-300 mx-auto" />
                    <p className="text-sm text-gray-500 mt-3">
                      No workflows found
                    </p>
                    <p className="text-xs text-gray-400 mt-1">
                      {temporalConnected
                        ? "Workflows will appear here when started"
                        : "Connect Temporal server to view workflows"}
                    </p>
                  </td>
                </tr>
              ) : (
                filteredWorkflows.map((workflow) => (
                  <tr
                    key={`${workflow.workflowId}-${workflow.runId}`}
                    className="hover:bg-gray-50 transition-colors"
                  >
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-2">
                        {getWorkflowTypeIcon(workflow.type)}
                        <div>
                          <p className="text-sm font-medium text-gray-900 truncate max-w-[200px]">
                            {workflow.workflowId}
                          </p>
                          <p className="text-xs text-gray-400 truncate max-w-[200px]">
                            {workflow.runId}
                          </p>
                        </div>
                      </div>
                    </td>
                    <td className="px-4 py-3">
                      <span className="text-sm text-gray-600">
                        {workflow.type}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      {getStatusBadge(workflow.status)}
                    </td>
                    <td className="px-4 py-3">
                      <span className="text-sm text-gray-600">
                        {workflow.taskQueue}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <span className="text-sm text-gray-600">
                        {formatTime(workflow.startTime)}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <span className="text-sm text-gray-600">
                        {formatDuration(workflow.startTime, workflow.closeTime)}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-end gap-2">
                        <button
                          onClick={() => handleViewDetails(workflow)}
                          className="p-1.5 text-gray-500 hover:text-brand-green hover:bg-brand-green/10 rounded-lg transition-colors"
                          title="View Details"
                        >
                          <Eye className="w-4 h-4" />
                        </button>
                        {workflow.status === "RUNNING" && (
                          <>
                            <button
                              onClick={() =>
                                handleWorkflowAction(
                                  workflow.workflowId,
                                  "cancel",
                                )
                              }
                              disabled={
                                actionLoading ===
                                `${workflow.workflowId}-cancel`
                              }
                              className="p-1.5 text-gray-500 hover:text-amber-600 hover:bg-amber-50 rounded-lg transition-colors disabled:opacity-50"
                              title="Cancel Workflow"
                            >
                              {actionLoading ===
                              `${workflow.workflowId}-cancel` ? (
                                <Loader2 className="w-4 h-4 animate-spin" />
                              ) : (
                                <Pause className="w-4 h-4" />
                              )}
                            </button>
                            <button
                              onClick={() =>
                                handleWorkflowAction(
                                  workflow.workflowId,
                                  "terminate",
                                  { reason: "Terminated by staff" },
                                )
                              }
                              disabled={
                                actionLoading ===
                                `${workflow.workflowId}-terminate`
                              }
                              className="p-1.5 text-gray-500 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors disabled:opacity-50"
                              title="Terminate Workflow"
                            >
                              {actionLoading ===
                              `${workflow.workflowId}-terminate` ? (
                                <Loader2 className="w-4 h-4 animate-spin" />
                              ) : (
                                <Ban className="w-4 h-4" />
                              )}
                            </button>
                          </>
                        )}
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Workflow Details Modal */}
      {selectedWorkflow && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-xl max-w-2xl w-full max-h-[80vh] overflow-hidden">
            <div className="p-6 border-b border-gray-100 flex items-center justify-between">
              <div>
                <h3 className="text-lg font-semibold text-gray-900">
                  Workflow Details
                </h3>
                <p className="text-sm text-gray-500 mt-0.5">
                  {selectedWorkflow.workflowId}
                </p>
              </div>
              <button
                onClick={() => {
                  setSelectedWorkflow(null);
                  setWorkflowDetails(null);
                }}
                className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <XCircle className="w-5 h-5" />
              </button>
            </div>

            <div className="p-6 overflow-y-auto max-h-[60vh]">
              {loadingDetails ? (
                <div className="flex items-center justify-center py-12">
                  <Loader2 className="w-8 h-8 text-gray-400 animate-spin" />
                </div>
              ) : workflowDetails ? (
                <div className="space-y-6">
                  {/* Status & Type */}
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <p className="text-xs font-medium text-gray-500 uppercase">
                        Status
                      </p>
                      <div className="mt-1">
                        {getStatusBadge(workflowDetails.status)}
                      </div>
                    </div>
                    <div>
                      <p className="text-xs font-medium text-gray-500 uppercase">
                        Type
                      </p>
                      <p className="text-sm text-gray-900 mt-1">
                        {workflowDetails.type}
                      </p>
                    </div>
                  </div>

                  {/* Times */}
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <p className="text-xs font-medium text-gray-500 uppercase">
                        Started
                      </p>
                      <p className="text-sm text-gray-900 mt-1">
                        {formatTime(workflowDetails.startTime)}
                      </p>
                    </div>
                    <div>
                      <p className="text-xs font-medium text-gray-500 uppercase">
                        Closed
                      </p>
                      <p className="text-sm text-gray-900 mt-1">
                        {formatTime(workflowDetails.closeTime)}
                      </p>
                    </div>
                  </div>

                  {/* Task Queue */}
                  <div>
                    <p className="text-xs font-medium text-gray-500 uppercase">
                      Task Queue
                    </p>
                    <p className="text-sm text-gray-900 mt-1">
                      {workflowDetails.taskQueue}
                    </p>
                  </div>

                  {/* Run ID */}
                  <div>
                    <p className="text-xs font-medium text-gray-500 uppercase">
                      Run ID
                    </p>
                    <p className="text-sm text-gray-900 mt-1 font-mono break-all">
                      {workflowDetails.runId}
                    </p>
                  </div>

                  {/* History Button */}
                  <div className="pt-4 border-t border-gray-100">
                    <button
                      onClick={() =>
                        handleWorkflowAction(
                          selectedWorkflow.workflowId,
                          "history",
                        )
                      }
                      disabled={
                        actionLoading ===
                        `${selectedWorkflow.workflowId}-history`
                      }
                      className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50"
                    >
                      {actionLoading ===
                      `${selectedWorkflow.workflowId}-history` ? (
                        <Loader2 className="w-4 h-4 animate-spin" />
                      ) : (
                        <History className="w-4 h-4" />
                      )}
                      View History
                    </button>
                  </div>

                  {/* History Events */}
                  {workflowDetails.history && (
                    <div className="pt-4 border-t border-gray-100">
                      <p className="text-xs font-medium text-gray-500 uppercase mb-3">
                        Event History ({workflowDetails.history.length} events)
                      </p>
                      <div className="max-h-60 overflow-y-auto space-y-2">
                        {workflowDetails.history.map(
                          (event: any, index: number) => (
                            <div
                              key={index}
                              className="text-xs bg-gray-50 rounded-lg p-2 font-mono"
                            >
                              <span className="text-gray-400">
                                #{event.eventId}
                              </span>{" "}
                              <span className="text-gray-700">
                                {event.eventType}
                              </span>{" "}
                              <span className="text-gray-400">
                                {event.eventTime}
                              </span>
                            </div>
                          ),
                        )}
                      </div>
                    </div>
                  )}
                </div>
              ) : (
                <p className="text-sm text-gray-500 text-center py-8">
                  Failed to load workflow details
                </p>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
