import React, { useMemo } from 'react';
import { ArrowUpRight, LayoutGrid } from 'lucide-react';
import { useWorkflows, type Workflow } from '../../contexts/WorkflowsContext';
import { useApplyWorkflow } from '../../hooks/useApplyWorkflow';

interface WorkflowsHomeProps {
  onBrowseAll: () => void;
}

const MAX_CARDS = 4;

/** Empty-state grid of pinned / most-used workflows with a "Browse all" link. */
const WorkflowsHome: React.FC<WorkflowsHomeProps> = ({ onBrowseAll }) => {
  const { workflows } = useWorkflows();
  const applyWorkflow = useApplyWorkflow();

  // Order: pinned first, then most-used, then recent (Array.sort is stable, so
  // ties keep the underlying built-ins-then-user ordering).
  const shown = useMemo<Workflow[]>(() => {
    return [...workflows]
      .sort((a, b) => Number(b.pinned) - Number(a.pinned) || (b.useCount ?? 0) - (a.useCount ?? 0))
      .slice(0, MAX_CARDS);
  }, [workflows]);

  return (
    <section className="mb-4 sm:mb-8">
      <div className="mb-3 flex items-center justify-between gap-3">
        <span className="text-xs font-semibold uppercase tracking-wide text-app-muted">Workflows</span>
        <button
          type="button"
          onClick={onBrowseAll}
          className="flex items-center gap-1.5 rounded-md text-xs font-medium text-brand-text transition-colors hover:underline focus:outline-none focus-visible:ring-2 focus-visible:ring-brand"
        >
          <LayoutGrid size={14} /> Browse all
        </button>
      </div>
      <div className="grid grid-cols-1 gap-2.5 sm:grid-cols-2">
        {shown.map((workflow) => (
          <button
            key={workflow.id}
            type="button"
            onClick={() => applyWorkflow(workflow)}
            className="group relative flex h-full w-full items-center justify-between gap-3 overflow-hidden rounded-xl border border-app-border bg-app-surface px-4 py-3 text-left transition-all duration-150 ease-out hover:border-brand/40 hover:bg-app-surface-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-brand"
          >
            <span className="min-w-0">
              <span className="block truncate text-[0.9rem] font-medium text-app-text">{workflow.title}</span>
              {workflow.description && (
                <span className="mt-0.5 block truncate text-[0.8rem] text-app-muted">{workflow.description}</span>
              )}
            </span>
            <ArrowUpRight
              size={16}
              className="shrink-0 text-app-muted opacity-0 transition-all duration-150 group-hover:text-brand-text group-hover:opacity-100"
            />
          </button>
        ))}
      </div>
    </section>
  );
};

export default React.memo(WorkflowsHome);
