/**
 * WorkflowCard Component
 * Reusable card component for displaying workflow feature status and actions
 * Supports active/inactive/error/locked states with metrics, last run info, and action buttons
 */

"use client";

import classNames from "classnames";
import {
  Lock,
  CheckCircle2,
  XCircle,
  AlertCircle,
  Settings,
  Play,
  Square,
  Clock,
} from "lucide-react";
import type { WorkflowCardProps } from "@/lib/types/workflow-ui.types";

export default function WorkflowCard({
  title,
  description,
  icon,
  status,
  metrics = [],
  lastRun,
  lastRunStatus,
  locked = false,
  requiresUpgrade = false,
  upgradeTier,
  onActivate,
  onDeactivate,
  onConfigure,
  loading = false,
}: WorkflowCardProps) {
  // Status configuration
  const statusConfig = {
    active: {
      badge: "bg-emerald-100 text-emerald-700 border-emerald-200",
      icon: CheckCircle2,
      label: "Active",
      labelAr: "نشط",
    },
    inactive: {
      badge: "bg-slate-100 text-slate-600 border-slate-200",
      icon: XCircle,
      label: "Inactive",
      labelAr: "غير نشط",
    },
    error: {
      badge: "bg-red-100 text-red-700 border-red-200",
      icon: AlertCircle,
      label: "Error",
      labelAr: "خطأ",
    },
    locked: {
      badge: "bg-amber-100 text-amber-700 border-amber-200",
      icon: Lock,
      label: "Locked",
      labelAr: "مقفل",
    },
  };

  const currentStatus = statusConfig[status];
  const StatusIcon = currentStatus.icon;

  // Format last run time
  const formatLastRun = (date: Date) => {
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);

    if (diffMins < 1) return "Just now";
    if (diffMins < 60) return `${diffMins} min ago`;
    if (diffHours < 24) return `${diffHours} hours ago`;
    if (diffDays < 7) return `${diffDays} days ago`;
    return date.toLocaleDateString();
  };

  return (
    <div
      className={classNames(
        "relative rounded-xl bg-white shadow-sm border-2 transition-all duration-200 min-h-[200px] flex flex-col",
        {
          "border-slate-200 hover:border-brand-green hover:shadow-md":
            !locked && !loading,
          "border-amber-300": locked,
          "border-red-300": status === "error",
          "border-emerald-300": status === "active",
          "opacity-75": loading,
        },
      )}
    >
      {/* Locked Overlay */}
      {locked && (
        <div className="absolute inset-0 z-10 flex flex-col items-center justify-center rounded-xl bg-white/95 backdrop-blur-sm">
          <Lock className="h-12 w-12 text-amber-500 mb-3" />
          <h4 className="text-lg font-bold text-slate-900 mb-1">
            Feature Locked
          </h4>
          <p className="text-sm text-slate-600 mb-4 text-center px-4">
            {requiresUpgrade && upgradeTier
              ? `Upgrade to ${upgradeTier} to unlock this feature`
              : "This feature is not available on your current plan"}
          </p>
          {requiresUpgrade && (
            <button
              className="rounded-lg bg-brand-green px-6 py-2 text-sm font-semibold text-white hover:bg-brand-greenHover transition-colors"
              onClick={() => {
                // In real implementation, this would open upgrade modal
                console.log("Upgrade clicked");
              }}
            >
              Upgrade Now
            </button>
          )}
        </div>
      )}

      {/* Card Content */}
      <div className="p-6 flex flex-col flex-1">
        {/* Header */}
        <div className="flex items-start gap-3 mb-4">
          <div className="flex items-start gap-3 flex-1 min-w-0">
            {/* Icon */}
            {icon && (
              <div className="flex-shrink-0 rounded-lg bg-slate-50 p-3 text-brand-green">
                {icon}
              </div>
            )}

            {/* Title and Description */}
            <div className="flex-1 min-w-0">
              <h3 className="text-lg font-bold text-slate-900 mb-1 truncate">
                {title}
              </h3>
              <p className="text-sm text-slate-600 line-clamp-2">
                {description}
              </p>
            </div>
          </div>

          {/* Status Badge */}
          <div
            className={classNames(
              "flex-shrink-0 flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-semibold whitespace-nowrap",
              currentStatus.badge,
            )}
          >
            <StatusIcon className="h-3.5 w-3.5 flex-shrink-0" />
            <span>{currentStatus.label}</span>
          </div>
        </div>

        {/* Metrics Grid */}
        {metrics.length > 0 && (
          <div className="grid grid-cols-2 gap-3 mb-4">
            {metrics.map((metric, index) => (
              <div
                key={index}
                className="rounded-lg bg-slate-50 p-3 border border-slate-100"
              >
                <div className="flex items-center gap-2 mb-1">
                  {metric.icon && (
                    <span className="text-slate-600">{metric.icon}</span>
                  )}
                  <p className="text-xs font-medium text-slate-600">
                    {metric.label}
                  </p>
                </div>
                <p className="text-lg font-bold text-slate-900">
                  {metric.value}
                </p>
              </div>
            ))}
          </div>
        )}

        {/* Last Run Info */}
        {lastRun && (
          <div className="flex items-center gap-2 mb-4 p-3 rounded-lg bg-slate-50 border border-slate-100">
            <Clock className="h-4 w-4 text-slate-500 flex-shrink-0" />
            <div className="flex-1 min-w-0">
              <p className="text-xs text-slate-600">
                Last run:{" "}
                <span className="font-medium">{formatLastRun(lastRun)}</span>
              </p>
              {lastRunStatus && (
                <p className="text-xs text-slate-500 truncate">
                  {lastRunStatus}
                </p>
              )}
            </div>
          </div>
        )}

        {/* Action Buttons */}
        <div className="flex items-center gap-2 mt-auto pt-2">
          {/* Activate/Deactivate */}
          {status === "inactive" && onActivate && (
            <button
              onClick={onActivate}
              disabled={loading}
              className={classNames(
                "flex-1 flex items-center justify-center gap-2 rounded-lg px-4 py-2.5 text-sm font-semibold transition-colors",
                "bg-brand-green text-white hover:bg-brand-greenHover",
                "disabled:opacity-50 disabled:cursor-not-allowed",
              )}
            >
              <Play className="h-4 w-4" />
              <span>{loading ? "Activating..." : "Activate"}</span>
            </button>
          )}

          {status === "active" && onDeactivate && (
            <button
              onClick={onDeactivate}
              disabled={loading}
              className={classNames(
                "flex-1 flex items-center justify-center gap-2 rounded-lg px-4 py-2.5 text-sm font-semibold transition-colors",
                "bg-slate-100 text-slate-700 hover:bg-slate-200",
                "disabled:opacity-50 disabled:cursor-not-allowed",
              )}
            >
              <Square className="h-4 w-4" />
              <span>{loading ? "Deactivating..." : "Deactivate"}</span>
            </button>
          )}

          {status === "error" && onActivate && (
            <button
              onClick={onActivate}
              disabled={loading}
              className={classNames(
                "flex-1 flex items-center justify-center gap-2 rounded-lg px-4 py-2.5 text-sm font-semibold transition-colors",
                "bg-red-600 text-white hover:bg-red-700",
                "disabled:opacity-50 disabled:cursor-not-allowed",
              )}
            >
              <Play className="h-4 w-4" />
              <span>{loading ? "Retrying..." : "Retry"}</span>
            </button>
          )}

          {/* Configure Button - always show with text when no other action buttons */}
          {onConfigure && (
            <button
              onClick={onConfigure}
              disabled={loading}
              aria-label="Configure workflow"
              className={classNames(
                "flex items-center justify-center gap-2 rounded-lg px-4 py-2.5 text-sm font-semibold transition-colors",
                "border-2 border-slate-200 bg-white text-slate-700 hover:border-brand-green hover:bg-slate-50",
                "disabled:opacity-50 disabled:cursor-not-allowed",
                // If no action button is shown, make configure button full width
                {
                  "flex-1":
                    !(status === "inactive" && onActivate) &&
                    !(status === "active" && onDeactivate) &&
                    !(status === "error" && onActivate),
                },
              )}
            >
              <Settings className="h-4 w-4" />
              <span>Configure</span>
            </button>
          )}
        </div>
      </div>

      {/* Loading Overlay */}
      {loading && (
        <div className="absolute inset-0 flex items-center justify-center rounded-xl bg-white/50 backdrop-blur-sm">
          <div className="flex flex-col items-center gap-2">
            <div className="h-8 w-8 animate-spin rounded-full border-4 border-slate-200 border-t-brand-green"></div>
            <p className="text-xs font-medium text-slate-600">Loading...</p>
          </div>
        </div>
      )}
    </div>
  );
}
