import { useState } from 'react'
import { AlertTriangle } from 'lucide-react'
import { useQuery } from '@tanstack/react-query'
import Modal from '../shared/Modal'
import {
  listMaterials,
  batchCreateAliases,
  type UnmappedMaterial,
  type Material,
} from '../../api/materials'

interface Props {
  unmapped: UnmappedMaterial[]
  onResolved: () => void
  onCancel: () => void
}

export default function UnmappedMaterialsDialog({ unmapped, onResolved, onCancel }: Props) {
  const [mappings, setMappings] = useState<Record<string, string>>({})
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // Load all library materials for the "all materials" fallback in dropdowns
  const { data: allMaterials } = useQuery({
    queryKey: ['materials'],
    queryFn: listMaterials,
  })

  const libraryMaterials = (allMaterials ?? []).filter(
    (m: Material) => m.schaeffler_code !== null
  )

  const allMapped = unmapped.every((u) => mappings[u.raw_name])

  async function handleProceed() {
    setSaving(true)
    setError(null)
    try {
      const batch = unmapped.map((u) => ({
        alias: u.raw_name,
        material_id: mappings[u.raw_name],
      }))
      await batchCreateAliases(batch)
      onResolved()
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Failed to create aliases')
    } finally {
      setSaving(false)
    }
  }

  return (
    <Modal title="Unmapped Materials" onClose={onCancel} size="lg">
      <div className="p-6 space-y-4">
        {/* Warning banner */}
        <div className="flex items-start gap-3 p-3 rounded-lg bg-amber-500/10 border border-amber-500/30">
          <AlertTriangle className="w-5 h-5 text-amber-500 shrink-0 mt-0.5" />
          <p className="text-sm text-content-secondary">
            The following materials have no alias to a library material.
            Map them before rendering to avoid magenta placeholder materials.
          </p>
        </div>

        {/* Mapping table */}
        <div className="space-y-3">
          {unmapped.map((u) => (
            <div
              key={u.raw_name}
              className="flex items-center gap-4 p-3 rounded-lg border border-border-default"
            >
              <div className="flex-1 min-w-0">
                <span className="text-sm font-medium text-content truncate block">
                  {u.raw_name}
                </span>
              </div>
              <div className="w-72 shrink-0">
                <select
                  className="w-full text-sm rounded-md border border-border-default px-3 py-1.5 text-content"
                  style={{ backgroundColor: 'var(--color-bg-surface)' }}
                  value={mappings[u.raw_name] ?? ''}
                  onChange={(e) =>
                    setMappings((prev) => ({ ...prev, [u.raw_name]: e.target.value }))
                  }
                >
                  <option value="">Select library material...</option>
                  {/* Suggestions first */}
                  {u.suggestions.length > 0 && (
                    <optgroup label="Suggestions">
                      {u.suggestions.map((s) => (
                        <option key={s.id} value={s.id}>
                          {s.name}
                        </option>
                      ))}
                    </optgroup>
                  )}
                  {/* All library materials */}
                  <optgroup label="All Library Materials">
                    {libraryMaterials
                      .sort((a: Material, b: Material) => a.name.localeCompare(b.name))
                      .map((m: Material) => (
                        <option key={m.id} value={m.id}>
                          {m.name}
                        </option>
                      ))}
                  </optgroup>
                </select>
              </div>
            </div>
          ))}
        </div>

        {error && (
          <p className="text-sm text-red-500">{error}</p>
        )}

        {/* Actions */}
        <div className="flex justify-end gap-3 pt-2">
          <button
            onClick={onCancel}
            className="px-4 py-2 text-sm rounded-md border border-border-default text-content-secondary hover:bg-surface-muted"
          >
            Cancel
          </button>
          <button
            onClick={handleProceed}
            disabled={!allMapped || saving}
            className="px-4 py-2 text-sm rounded-md bg-brand text-white hover:bg-brand-hover disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {saving ? 'Saving...' : 'Map All & Proceed'}
          </button>
        </div>
      </div>
    </Modal>
  )
}
