import React, { useMemo, useState } from 'react';
import { Copy, Pencil, Plus, Search, Star, Trash2 } from 'lucide-react';
import { Button, ModalShell, StatusBadge } from '../ui';
import { cn } from '../../utils/classNames';
import { useIsWorkflowsModalOpen, useSetIsWorkflowsModalOpen } from '../../contexts/UIContext';
import { useWorkflows, type Workflow } from '../../contexts/WorkflowsContext';
import { useApplyWorkflow } from '../../hooks/useApplyWorkflow';
import WorkflowBuilder from './WorkflowBuilder';

interface WorkflowRowProps {
  workflow: Workflow;
  onApply: (workflow: Workflow) => void;
  onEdit: (workflow: Workflow) => void;
  onDuplicate: (id: string) => void;
  onDelete: (id: string) => void;
  onTogglePin: (id: string) => void;
}

const iconButton =
  'flex h-7 w-7 items-center justify-center rounded-md text-app-muted transition-colors hover:bg-app-surface-hover hover:text-app-text focus:outline-none focus-visible:ring-2 focus-visible:ring-brand';

const WorkflowRow: React.FC<WorkflowRowProps> = ({ workflow, onApply, onEdit, onDuplicate, onDelete, onTogglePin }) => (
  <div className="group flex items-start gap-2 rounded-lg border border-app-border p-3 transition-colors hover:border-brand/40">
    <button type="button" onClick={() => onApply(workflow)} className="min-w-0 flex-1 text-left focus:outline-none">
      <div className="flex items-center gap-2">
        <span className="truncate text-sm font-medium text-app-text">{workflow.title}</span>
        {workflow.scope === 'user' && <StatusBadge tone="neutral">Custom</StatusBadge>}
      </div>
      {workflow.description && <p className="mt-0.5 truncate text-xs text-app-muted">{workflow.description}</p>}
      {workflow.variables.length > 0 && (
        <div className="mt-1.5 flex flex-wrap gap-1">
          {workflow.variables.map((variable) => (
            <span key={variable.key} className="rounded border border-brand/20 bg-brand-subtle px-1.5 py-0.5 text-[0.7rem] font-medium text-brand-text">
              {variable.label}
            </span>
          ))}
        </div>
      )}
    </button>
    <div className="flex items-center gap-0.5">
      <button
        type="button"
        onClick={() => onTogglePin(workflow.id)}
        aria-label={workflow.pinned ? 'Unpin' : 'Pin'}
        aria-pressed={workflow.pinned}
        className={cn(iconButton, workflow.pinned ? 'text-brand opacity-100 hover:text-brand' : 'opacity-0 group-hover:opacity-100')}
      >
        <Star size={15} className={workflow.pinned ? 'fill-current' : ''} />
      </button>
      {workflow.scope === 'user' && (
        <button type="button" onClick={() => onEdit(workflow)} aria-label="Edit" className={cn(iconButton, 'opacity-0 group-hover:opacity-100')}>
          <Pencil size={14} />
        </button>
      )}
      <button type="button" onClick={() => onDuplicate(workflow.id)} aria-label="Duplicate" className={cn(iconButton, 'opacity-0 group-hover:opacity-100')}>
        <Copy size={14} />
      </button>
      {workflow.scope === 'user' && (
        <button type="button" onClick={() => onDelete(workflow.id)} aria-label="Delete" className={cn(iconButton, 'opacity-0 hover:text-danger group-hover:opacity-100')}>
          <Trash2 size={14} />
        </button>
      )}
    </div>
  </div>
);

const WorkflowsLibraryModal: React.FC = () => {
  const open = useIsWorkflowsModalOpen();
  const setOpen = useSetIsWorkflowsModalOpen();
  const { workflows, duplicateWorkflow, deleteWorkflow, togglePin } = useWorkflows();
  const applyWorkflow = useApplyWorkflow();

  const [query, setQuery] = useState('');
  const [builder, setBuilder] = useState<{ active: boolean; workflow: Workflow | null }>({ active: false, workflow: null });

  const close = () => {
    setBuilder({ active: false, workflow: null });
    setQuery('');
    setOpen(false);
  };

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return workflows;
    return workflows.filter((workflow) =>
      `${workflow.title} ${workflow.description ?? ''} ${workflow.template}`.toLowerCase().includes(q),
    );
  }, [workflows, query]);

  const pinned = filtered.filter((workflow) => workflow.pinned);
  const rest = filtered.filter((workflow) => !workflow.pinned);

  const apply = (workflow: Workflow) => {
    applyWorkflow(workflow);
    close();
  };

  const rowProps = {
    onApply: apply,
    onEdit: (workflow: Workflow) => setBuilder({ active: true, workflow }),
    onDuplicate: (id: string) => duplicateWorkflow(id),
    onDelete: (id: string) => deleteWorkflow(id),
    onTogglePin: togglePin,
  };

  return (
    <ModalShell
      open={open}
      title={builder.active ? (builder.workflow ? 'Edit workflow' : 'New workflow') : 'Workflows'}
      maxWidthClass="max-w-2xl"
      onClose={close}
    >
      {builder.active ? (
        <WorkflowBuilder workflow={builder.workflow} onClose={() => setBuilder({ active: false, workflow: null })} />
      ) : (
        <div className="space-y-4">
          <div className="flex items-center gap-2">
            <div className="relative min-w-0 flex-1">
              <Search size={16} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-app-muted" />
              <input
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder="Search workflows"
                aria-label="Search workflows"
                className="w-full rounded-md border border-app-border bg-app-surface py-2 pl-9 pr-3 text-sm text-app-text outline-none transition placeholder:text-app-muted focus:border-brand focus:ring-2 focus:ring-brand/20"
              />
            </div>
            <Button variant="primary" onClick={() => setBuilder({ active: true, workflow: null })}>
              <Plus size={16} /> New
            </Button>
          </div>

          {filtered.length === 0 ? (
            <p className="rounded-lg border border-app-border p-6 text-center text-sm text-app-muted">No workflows match "{query}".</p>
          ) : query.trim() ? (
            <div className="space-y-2">
              {filtered.map((workflow) => <WorkflowRow key={workflow.id} workflow={workflow} {...rowProps} />)}
            </div>
          ) : (
            <div className="space-y-5">
              {pinned.length > 0 && (
                <div className="space-y-2">
                  <h4 className="text-xs font-semibold uppercase tracking-wide text-app-muted-strong">Pinned</h4>
                  {pinned.map((workflow) => <WorkflowRow key={workflow.id} workflow={workflow} {...rowProps} />)}
                </div>
              )}
              <div className="space-y-2">
                <h4 className="text-xs font-semibold uppercase tracking-wide text-app-muted-strong">All workflows</h4>
                {rest.map((workflow) => <WorkflowRow key={workflow.id} workflow={workflow} {...rowProps} />)}
              </div>
            </div>
          )}
        </div>
      )}
    </ModalShell>
  );
};

export default WorkflowsLibraryModal;
