import { useState } from 'react';
import { Grid2x2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { extractApiError } from '@/api/client';
import type { MitreTechnique, MitreTacticRef } from '@/api/types';
import { useUpdateSimulation } from '@/hooks/useSimulations';
import { useToast } from '@/hooks/useToast';
import { MitreTechniqueTag, MitreTacticTag } from './MitreTechniqueTag';
import { MitreTechniquePicker } from './MitreTechniquePicker';
import { MitreMatrixModal } from './MitreMatrixModal';
import type { MatrixSelection } from './MitreMatrixModal';

interface MitreTechniquesFieldProps {
  value: MitreTechnique[];
  tactics: MitreTacticRef[];
  simulationId: number;
  engagementId: number;
  disabled?: boolean;
}

export function MitreTechniquesField({
  value,
  tactics,
  simulationId,
  engagementId,
  disabled = false,
}: MitreTechniquesFieldProps): JSX.Element {
  const { t } = useTranslation();
  const [showMatrix, setShowMatrix] = useState(false);
  const [showPicker, setShowPicker] = useState(false);

  const { push } = useToast();
  const updateMutation = useUpdateSimulation(simulationId, engagementId);

  const save = async (techniques: MitreTechnique[], nextTactics: MitreTacticRef[]) => {
    try {
      await updateMutation.mutateAsync({
        technique_ids: techniques.map((tech) => tech.id),
        tactic_ids: nextTactics.map((tac) => tac.id),
      });
      push(t('mitre.field.savedToast'), 'success');
    } catch (err) {
      push(extractApiError(err, t('mitre.field.errorToast')), 'error');
    }
  };

  const handleRemoveTechnique = (id: string) => {
    void save(value.filter((tech) => tech.id !== id), tactics);
  };

  const handleRemoveTactic = (id: string) => {
    void save(value, tactics.filter((tac) => tac.id !== id));
  };

  const handleSelect = (technique: MitreTechnique) => {
    if (value.some((tech) => tech.id === technique.id)) return;
    void save([...value, technique], tactics);
    setShowPicker(false);
  };

  const handleMatrixApply = ({ techniques, tactics: newTactics }: MatrixSelection) => {
    setShowMatrix(false);
    const merged = techniques.map((sel) => {
      const existing = value.find((v) => v.id === sel.id);
      return existing ?? sel;
    });
    void save(merged, newTactics);
  };

  const isPending = updateMutation.isPending;
  const isEmpty = value.length === 0 && tactics.length === 0;

  return (
    <div className="flex flex-col gap-sm">
      {/* Chips area */}
      {isEmpty ? (
        <p className="text-[13px] text-graphite">{t('mitre.field.empty')}</p>
      ) : (
        <div className="flex flex-wrap gap-xs" data-testid="techniques-tag-list">
          {tactics.map((tac) => (
            <MitreTacticTag
              key={tac.id}
              tactic={tac}
              onRemove={() => handleRemoveTactic(tac.id)}
              disabled={disabled || isPending}
            />
          ))}
          {value.map((tech) => (
            <MitreTechniqueTag
              key={tech.id}
              technique={tech}
              onRemove={() => handleRemoveTechnique(tech.id)}
              disabled={disabled || isPending}
            />
          ))}
        </div>
      )}

      {/* Input row — hidden in read-only mode */}
      {!disabled && (
        <div className="flex items-center gap-xs">
          <div className="flex-1 max-w-sm">
            {showPicker ? (
              <MitreTechniquePicker onSelect={handleSelect} disabled={isPending} />
            ) : (
              <button
                type="button"
                className="text-input h-9 text-[13px] text-graphite text-left cursor-text w-full"
                onClick={() => setShowPicker(true)}
                disabled={isPending}
              >
                {t('mitre.field.search')}
              </button>
            )}
          </div>
          <button
            type="button"
            aria-label={t('mitre.field.openMatrix')}
            onClick={() => { setShowPicker(false); setShowMatrix(true); }}
            disabled={isPending}
            className="flex-shrink-0 flex items-center justify-center w-9 h-9 rounded-none border border-steel text-graphite hover:text-ink hover:border-ink"
          >
            <Grid2x2 size={16} />
          </button>
          {isPending && <span className="text-[12px] text-graphite">{t('common.saving')}</span>}
        </div>
      )}

      <MitreMatrixModal
        isOpen={showMatrix}
        initialTechniques={value}
        initialTactics={tactics}
        onApply={handleMatrixApply}
        onCancel={() => setShowMatrix(false)}
      />
    </div>
  );
}
