'use client';

import * as React from 'react';
import Link from 'next/link';
import { Trash2, Settings2, X, AlertTriangle } from 'lucide-react';

import { ToolIcon, getEngineIcon } from '@/app/components/ui/tool-icons';
import AgentRunButton from '@/app/agents/agent-run-button';
import EngineModelPicker from '@/app/agents/engine-model-picker';

type EngineMeta = {
  id: string;
  label: string;
  available?: boolean;
  models?: { name: string }[];
  default_model?: string;
};

export interface AgentBuilderCardProps {
  agent: {
    id: string;
    name: string;
    title?: string | null;
    mission?: string;
    status?: string;
    engine: string;
    model?: string;
    schedule?: string;
    tools?: string[];
    last_heartbeat?: string;
    last_run_at?: string;
  };
  scheduleLabel: string;
  toolCategories: string[];
  engines: EngineMeta[];
  updateAction: (formData: FormData) => void | Promise<void>;
  deleteAction: (formData: FormData) => void | Promise<void>;
  className?: string;
}

function relativeTime(iso?: string) {
  if (!iso) return null;
  const then = new Date(iso).getTime();
  if (Number.isNaN(then)) return null;
  const diff = Date.now() - then;
  const minute = 60_000, hour = 3_600_000, day = 86_400_000;
  if (diff < minute) return 'just now';
  if (diff < hour) return `${Math.floor(diff / minute)}m`;
  if (diff < day) return `${Math.floor(diff / hour)}h`;
  if (diff < 7 * day) return `${Math.floor(diff / day)}d`;
  return iso.slice(0, 10);
}

type Tone = 'active' | 'idle' | 'error';

function normaliseStatus(raw?: string): { label: string; tone: Tone; full?: string } {
  const s = (raw || '').toLowerCase();
  if (!s) return { label: 'Idle', tone: 'idle' };
  if (s.includes('ok') || s.includes('complete') || s.includes('running')) {
    return { label: 'Active', tone: 'active', full: raw };
  }
  if (s.includes('fail') || s.includes('error') || s.includes('blocked')) {
    return { label: 'Error', tone: 'error', full: raw };
  }
  return { label: 'Idle', tone: 'idle', full: raw };
}

export function AgentBuilderCard({
  agent,
  scheduleLabel,
  toolCategories,
  engines,
  updateAction,
  deleteAction,
}: AgentBuilderCardProps) {
  const [enginePanel, setEnginePanel] = React.useState(false);
  const [confirmOpen, setConfirmOpen] = React.useState(false);
  const [confirmText, setConfirmText] = React.useState('');
  const confirmDialogRef = React.useRef<HTMLDialogElement | null>(null);
  const confirmInputRef = React.useRef<HTMLInputElement | null>(null);
  const confirmMatches = confirmText.trim() === 'DELETE';

  const closeConfirm = React.useCallback(() => {
    const node = confirmDialogRef.current;
    if (node && node.open) node.close();
    setConfirmOpen(false);
    setConfirmText('');
  }, []);

  const openConfirm = React.useCallback(() => {
    const node = confirmDialogRef.current;
    if (!node) return;
    setConfirmText('');
    if (typeof node.showModal === 'function') {
      node.showModal();
    } else {
      node.setAttribute('open', '');
    }
    setConfirmOpen(true);
  }, []);

  React.useEffect(() => {
    const node = confirmDialogRef.current;
    if (!node) return undefined;
    const onCancel = (event: Event) => {
      event.preventDefault();
      closeConfirm();
    };
    const onClose = () => {
      setConfirmOpen(false);
      setConfirmText('');
    };
    node.addEventListener('cancel', onCancel);
    node.addEventListener('close', onClose);
    return () => {
      node.removeEventListener('cancel', onCancel);
      node.removeEventListener('close', onClose);
    };
  }, [closeConfirm]);

  React.useEffect(() => {
    if (confirmOpen) {
      const t = window.setTimeout(() => confirmInputRef.current?.focus(), 50);
      return () => window.clearTimeout(t);
    }
    return undefined;
  }, [confirmOpen]);

  const engineLabel = engines.find(e => e.id === agent.engine)?.label || agent.engine;
  const engineEntry = getEngineIcon(agent.engine);
  const lastRun = relativeTime(agent.last_run_at || agent.last_heartbeat);
  const status = normaliseStatus(agent.status);

  return (
    <li className={`mkt-card agent-card-mkt ${status.tone === 'active' ? 'on' : ''}`}>
      <Link
        href={`/agents/${agent.id}`}
        prefetch={false}
        className="agent-card-link"
        aria-label={`Open ${agent.name}`}
      >
        <div className="mkt-card-head">
          <span
            className="mkt-chip-tile agent-card-tile"
            style={engineEntry ? { color: engineEntry.tint } : undefined}
            aria-hidden="true"
          >
            {engineEntry ? <engineEntry.Icon size={18} /> : (
              <span className="agent-card-tile-glyph">{agent.name.slice(0, 1).toUpperCase()}</span>
            )}
          </span>
          <span
            className={`agent-card-status tone-${status.tone}`}
            title={status.full || status.label}
          >
            <span className="agent-card-status-dot" aria-hidden />
            {status.label}
          </span>
        </div>

        <div className="mkt-card-body">
          <h3 className="mkt-card-title">{agent.name}</h3>
          {agent.title ? (
            <span className="agent-card-role-tag">{agent.title}</span>
          ) : null}
          {agent.mission ? (
            <p className="mkt-card-desc">{agent.mission}</p>
          ) : null}
        </div>

        <div className="mkt-card-meta">
          <span>Engine <b>{engineLabel}</b></span>
          {agent.model ? <span>Model <b>{agent.model}</b></span> : null}
          <span>Schedule <b>{scheduleLabel}</b></span>
          <span>Last run <b>{lastRun ? `${lastRun} ago` : 'never'}</b></span>
        </div>
      </Link>

      <div className="mkt-card-foot agent-card-foot">
        <div className="agent-card-tools">
          {toolCategories.slice(0, 6).map((category) => (
            <span
              key={category}
              title={category}
              className="agent-card-tool"
              aria-hidden="true"
            >
              <ToolIcon category={category} size={12} />
            </span>
          ))}
          {toolCategories.length === 0 ? (
            <span className="agent-card-tools-empty">no tools</span>
          ) : null}
        </div>
        <div className="agent-card-actions">
          <AgentRunButton agentId={agent.id} />
          <button
            type="button"
            aria-label="Change engine"
            title="Change engine"
            onClick={() => setEnginePanel(v => !v)}
            className={`admin-button secondary icon ${enginePanel ? 'on' : ''}`}
          >
            <Settings2 size={13} />
          </button>
          <button
            type="button"
            aria-label="Delete agent"
            title="Delete agent"
            onClick={openConfirm}
            className="admin-button danger icon"
          >
            <Trash2 size={13} />
          </button>
        </div>
      </div>

      {enginePanel ? (
        <form action={updateAction} className="agent-card-engine-form">
          <input type="hidden" name="agent_id" value={agent.id} />
          <div className="agent-engine-form">
            <EngineModelPicker
              engines={engines}
              initialEngine={agent.engine}
              initialModel={agent.model || ''}
            />
            <button type="submit" className="admin-button">Save</button>
            <button
              type="button"
              onClick={() => setEnginePanel(false)}
              className="admin-button secondary"
            >
              Cancel
            </button>
          </div>
        </form>
      ) : null}

      <dialog
        ref={confirmDialogRef}
        className="agent-delete-dialog"
        onClick={(event) => {
          if (event.target === confirmDialogRef.current) closeConfirm();
        }}
      >
        {confirmOpen ? (
          <div
            className="agent-delete-modal"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="agent-delete-modal-head">
              <div className="agent-delete-modal-title">
                <span className="agent-delete-modal-icon" aria-hidden>
                  <AlertTriangle size={16} />
                </span>
                <div>
                  <h3>Delete agent</h3>
                  <p>This action cannot be undone.</p>
                </div>
              </div>
              <button
                type="button"
                onClick={closeConfirm}
                aria-label="Close"
                className="agent-delete-modal-close"
              >
                <X size={14} />
              </button>
            </div>

            <form
              action={deleteAction}
              onSubmit={(event) => {
                if (!confirmMatches) {
                  event.preventDefault();
                  return;
                }
                setConfirmOpen(false);
              }}
              className="agent-delete-modal-body"
            >
              <input type="hidden" name="agent_id" value={agent.id} />
              <p>
                You are about to permanently delete{' '}
                <b>{agent.name}</b>. Its runs, schedules, and workspace files will be removed.
              </p>
              <label className="agent-delete-confirm-label">
                <span>
                  Type <code>DELETE</code> to confirm
                </span>
                <input
                  ref={confirmInputRef}
                  type="text"
                  value={confirmText}
                  onChange={(e) => setConfirmText(e.target.value)}
                  autoComplete="off"
                  spellCheck={false}
                  placeholder="DELETE"
                />
              </label>

              <div className="agent-delete-modal-actions">
                <button
                  type="button"
                  onClick={closeConfirm}
                  className="admin-button secondary"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={!confirmMatches}
                  className="admin-button danger"
                >
                  Delete agent
                </button>
              </div>
            </form>
          </div>
        ) : null}
      </dialog>
    </li>
  );
}
