import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { Plus, Trash2, Pencil, Check, X } from 'lucide-react'
import { listMaterials, createMaterial, updateMaterial, deleteMaterial } from '../../api/materials'
import type { Material } from '../../api/materials'

export default function MaterialLibrary() {
  const qc = useQueryClient()
  const [showAdd, setShowAdd] = useState(false)
  const [newName, setNewName] = useState('')
  const [newDesc, setNewDesc] = useState('')
  const [editingId, setEditingId] = useState<string | null>(null)
  const [editName, setEditName] = useState('')
  const [editDesc, setEditDesc] = useState('')

  const { data: materials = [] } = useQuery({
    queryKey: ['materials'],
    queryFn: listMaterials,
  })

  const createMut = useMutation({
    mutationFn: () => createMaterial({ name: newName.trim(), description: newDesc.trim() || undefined }),
    onSuccess: () => {
      toast.success('Material added')
      qc.invalidateQueries({ queryKey: ['materials'] })
      setShowAdd(false)
      setNewName('')
      setNewDesc('')
    },
    onError: (e: any) => toast.error(e.response?.data?.detail || 'Failed to add material'),
  })

  const updateMut = useMutation({
    mutationFn: (id: string) => updateMaterial(id, { name: editName.trim(), description: editDesc.trim() || undefined }),
    onSuccess: () => {
      toast.success('Material updated')
      qc.invalidateQueries({ queryKey: ['materials'] })
      setEditingId(null)
    },
    onError: (e: any) => toast.error(e.response?.data?.detail || 'Failed to update'),
  })

  const deleteMut = useMutation({
    mutationFn: deleteMaterial,
    onSuccess: () => {
      toast.success('Material deleted')
      qc.invalidateQueries({ queryKey: ['materials'] })
    },
    onError: (e: any) => toast.error(e.response?.data?.detail || 'Failed to delete'),
  })

  const startEdit = (mat: Material) => {
    setEditingId(mat.id)
    setEditName(mat.name)
    setEditDesc(mat.description ?? '')
  }

  return (
    <div className="card">
      <div className="p-4 border-b border-border-default flex items-center justify-between">
        <div>
          <h2 className="font-semibold text-content">Material Library</h2>
          <p className="text-xs text-content-muted mt-0.5">
            Shared materials available when assigning CAD part materials.
          </p>
        </div>
        <button onClick={() => setShowAdd(!showAdd)} className="btn-primary">
          <Plus size={16} /> Add Material
        </button>
      </div>

      {showAdd && (
        <div className="p-4 border-b border-border-light bg-surface-alt flex gap-3 items-end flex-wrap">
          <div className="flex-1 min-w-[160px]">
            <label className="block text-xs font-medium text-content-secondary mb-1">Name *</label>
            <input
              autoFocus
              placeholder="e.g. Steel 100Cr6"
              value={newName}
              onChange={(e) => setNewName(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && newName.trim() && createMut.mutate()}
              className="input-base"
            />
          </div>
          <div className="flex-1 min-w-[200px]">
            <label className="block text-xs font-medium text-content-secondary mb-1">Description</label>
            <input
              placeholder="e.g. Bearing steel, hardened"
              value={newDesc}
              onChange={(e) => setNewDesc(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && newName.trim() && createMut.mutate()}
              className="input-base"
            />
          </div>
          <div className="flex gap-2">
            <button
              onClick={() => createMut.mutate()}
              disabled={!newName.trim() || createMut.isPending}
              className="btn-primary text-sm"
            >
              {createMut.isPending ? 'Adding…' : 'Add'}
            </button>
            <button onClick={() => setShowAdd(false)} className="btn-secondary text-sm">Cancel</button>
          </div>
        </div>
      )}

      {materials.length === 0 ? (
        <div className="p-8 text-center text-content-muted text-sm">
          No materials yet. Add the first one above.
        </div>
      ) : (
        <div className="divide-y divide-border-light">
          {materials.map((mat) => (
            <div key={mat.id} className="flex items-center px-6 py-3 gap-3">
              {editingId === mat.id ? (
                <>
                  <input
                    autoFocus
                    value={editName}
                    onChange={(e) => setEditName(e.target.value)}
                    className="flex-1 px-2 py-1 border border-border-default rounded text-sm focus:outline-none focus:border-accent"
                  />
                  <input
                    value={editDesc}
                    onChange={(e) => setEditDesc(e.target.value)}
                    placeholder="Description"
                    className="flex-1 px-2 py-1 border border-border-default rounded text-sm focus:outline-none focus:border-accent"
                  />
                  <button
                    onClick={() => updateMut.mutate(mat.id)}
                    disabled={!editName.trim() || updateMut.isPending}
                    className="text-status-success-text hover:text-status-success-text"
                    title="Save"
                  >
                    <Check size={16} />
                  </button>
                  <button onClick={() => setEditingId(null)} className="text-content-muted hover:text-content-secondary" title="Cancel">
                    <X size={16} />
                  </button>
                </>
              ) : (
                <>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-content">{mat.name}</p>
                    {mat.description && (
                      <p className="text-xs text-content-muted">{mat.description}</p>
                    )}
                  </div>
                  <button onClick={() => startEdit(mat)} className="text-content-muted hover:text-content-secondary" title="Edit">
                    <Pencil size={15} />
                  </button>
                  <button
                    onClick={() => {
                      if (confirm(`Delete material "${mat.name}"?`)) deleteMut.mutate(mat.id)
                    }}
                    className="text-content-muted hover:text-red-500"
                    title="Delete"
                  >
                    <Trash2 size={15} />
                  </button>
                </>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
