import React, { useMemo, useState } from 'react';
import { ArrowLeft } from 'lucide-react';
import { Button } from '../ui';
import { deriveVariables, type WorkflowVariable } from '../../utils/workflowTemplate';
import { useWorkflows, type Workflow } from '../../contexts/WorkflowsContext';

interface WorkflowBuilderProps {
  /** Existing workflow to edit, or null to create a new one. */
  workflow: Workflow | null;
  onClose: () => void;
}

type VarMeta = Record<string, Partial<Omit<WorkflowVariable, 'key'>>>;

const fieldClass =
  'w-full rounded-md border border-app-border bg-app-surface px-3 py-2 text-sm text-app-text outline-none transition placeholder:text-app-muted focus:border-brand focus:ring-2 focus:ring-brand/20';

const WorkflowBuilder: React.FC<WorkflowBuilderProps> = ({ workflow, onClose }) => {
  const { createWorkflow, updateWorkflow } = useWorkflows();
  const [title, setTitle] = useState(workflow?.title ?? '');
  const [description, setDescription] = useState(workflow?.description ?? '');
  const [template, setTemplate] = useState(workflow?.template ?? '');
  const [varMeta, setVarMeta] = useState<VarMeta>(() => {
    const meta: VarMeta = {};
    workflow?.variables.forEach((variable) => {
      meta[variable.key] = {
        label: variable.label,
        placeholder: variable.placeholder,
        default: variable.default,
        required: variable.required,
      };
    });
    return meta;
  });

  const variables = useMemo(() => {
    const existing: WorkflowVariable[] = Object.entries(varMeta).map(([key, meta]) => ({
      key,
      label: meta.label ?? key,
      placeholder: meta.placeholder,
      default: meta.default,
      required: meta.required,
    }));
    return deriveVariables(template, existing);
  }, [template, varMeta]);

  const setMeta = (key: string, patch: Partial<Omit<WorkflowVariable, 'key'>>) => {
    setVarMeta((prev) => ({ ...prev, [key]: { ...prev[key], ...patch } }));
  };

  const insertVariable = () => {
    const next = `var${variables.length + 1}`;
    setTemplate((prev) => `${prev}{{${next}}}`);
  };

  const canSave = title.trim().length > 0 && template.trim().length > 0;

  const save = () => {
    if (!canSave) return;
    const input = { title: title.trim(), description: description.trim() || undefined, template: template.trim(), variables };
    if (workflow && workflow.scope === 'user') {
      updateWorkflow(workflow.id, input);
    } else {
      createWorkflow(input);
    }
    onClose();
  };

  return (
    <div className="space-y-4">
      <Button variant="ghost" size="sm" onClick={onClose}>
        <ArrowLeft size={15} /> Back
      </Button>

      <label className="block space-y-1.5">
        <span className="text-sm font-medium text-app-text">Title</span>
        <input className={fieldClass} value={title} onChange={(e) => setTitle(e.target.value)} placeholder="e.g. Draft a blog post" />
      </label>

      <label className="block space-y-1.5">
        <span className="text-sm font-medium text-app-text">Description <span className="text-app-muted">(optional)</span></span>
        <input className={fieldClass} value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Short helper text" />
      </label>

      <label className="block space-y-1.5">
        <div className="flex items-center justify-between">
          <span className="text-sm font-medium text-app-text">Prompt template</span>
          <button type="button" onClick={insertVariable} className="text-xs font-medium text-brand-text hover:underline">
            + Insert variable
          </button>
        </div>
        <textarea
          className={`${fieldClass} min-h-[7rem] resize-y scrollbar-custom`}
          value={template}
          onChange={(e) => setTemplate(e.target.value)}
          placeholder="Write a blog post about {{topic}} for {{audience}}…"
        />
        <span className="block text-xs text-app-muted">
          Wrap fill-in spots in double braces, e.g. <code className="rounded bg-app-surface-muted px-1">{'{{topic}}'}</code>.
        </span>
      </label>

      {variables.length > 0 && (
        <div className="space-y-2">
          <span className="text-sm font-medium text-app-text">Variables</span>
          {variables.map((variable) => (
            <div key={variable.key} className="rounded-lg border border-app-border p-3">
              <div className="mb-2 flex items-center gap-2">
                <code className="rounded bg-app-surface-muted px-1.5 py-0.5 text-xs text-app-text">{`{{${variable.key}}}`}</code>
                <label className="ml-auto flex items-center gap-1.5 text-xs text-app-muted">
                  <input
                    type="checkbox"
                    checked={variable.required ?? false}
                    onChange={(e) => setMeta(variable.key, { required: e.target.checked })}
                    className="accent-brand"
                  />
                  Required
                </label>
              </div>
              <div className="grid gap-2 sm:grid-cols-3">
                <input className={fieldClass} value={variable.label} onChange={(e) => setMeta(variable.key, { label: e.target.value })} placeholder="Label" />
                <input className={fieldClass} value={variable.placeholder ?? ''} onChange={(e) => setMeta(variable.key, { placeholder: e.target.value })} placeholder="Hint" />
                <input className={fieldClass} value={variable.default ?? ''} onChange={(e) => setMeta(variable.key, { default: e.target.value })} placeholder="Default" />
              </div>
            </div>
          ))}
        </div>
      )}

      <div className="flex justify-end gap-2 pt-1">
        <Button onClick={onClose}>Cancel</Button>
        <Button variant="primary" onClick={save} disabled={!canSave}>
          {workflow && workflow.scope === 'user' ? 'Save changes' : 'Create workflow'}
        </Button>
      </div>
    </div>
  );
};

export default WorkflowBuilder;
