import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { Upload, Trash2, RefreshCw, ChevronDown, ChevronRight, Library } from 'lucide-react'
import { useDropzone } from 'react-dropzone'
import {
  listAssetLibraries,
  createAssetLibrary,
  refreshAssetLibraryCatalog,
  deleteAssetLibrary,
} from '../api/assetLibraries'
import type { AssetLibrary } from '../api/assetLibraries'
import api from '../api/client'

// ── UploadModal ────────────────────────────────────────────────────────────

function UploadModal({ onClose }: { onClose: () => void }) {
  const qc = useQueryClient()
  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [file, setFile] = useState<File | null>(null)

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    accept: { 'application/octet-stream': ['.blend'] },
    multiple: false,
    onDrop: (files) => { if (files[0]) setFile(files[0]) },
  })

  const uploadMut = useMutation({
    mutationFn: () => {
      if (!file || !name.trim()) throw new Error('Name and file required')
      return createAssetLibrary({ name: name.trim(), description: description.trim() || undefined, blend_file: file })
    },
    onSuccess: () => {
      toast.success('Asset library uploaded')
      qc.invalidateQueries({ queryKey: ['asset-libraries'] })
      onClose()
    },
    onError: (e: any) => toast.error(e.response?.data?.detail || 'Upload failed'),
  })

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="bg-white rounded-xl shadow-2xl w-full max-w-lg flex flex-col">
        <div className="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
          <h2 className="text-lg font-semibold text-gray-900">Upload Asset Library</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600 text-xl leading-none">
            &times;
          </button>
        </div>
        <div className="px-6 py-4 space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Name <span className="text-red-500">*</span>
            </label>
            <input
              className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="e.g. Schaeffler Materials v2"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Description</label>
            <input
              className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="Optional description"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              .blend File <span className="text-red-500">*</span>
            </label>
            <div
              {...getRootProps()}
              className={`border-2 border-dashed rounded-lg p-6 text-center cursor-pointer transition-colors ${
                isDragActive ? 'border-blue-500 bg-blue-50' : 'border-gray-300 hover:border-blue-400'
              }`}
            >
              <input {...getInputProps()} />
              {file ? (
                <p className="text-sm text-gray-700 font-medium">{file.name}</p>
              ) : (
                <>
                  <Upload size={24} className="text-gray-400 mx-auto mb-2" />
                  <p className="text-sm text-gray-500">
                    {isDragActive ? 'Drop the .blend file here' : 'Drag & drop a .blend file, or click to browse'}
                  </p>
                </>
              )}
            </div>
          </div>
        </div>
        <div className="px-6 py-4 border-t border-gray-200 flex justify-end gap-3">
          <button
            onClick={onClose}
            className="px-4 py-2 text-sm bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition-colors"
          >
            Cancel
          </button>
          <button
            onClick={() => uploadMut.mutate()}
            disabled={!name.trim() || !file || uploadMut.isPending}
            className="px-4 py-2 text-sm bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
          >
            <Upload size={14} />
            {uploadMut.isPending ? 'Uploading...' : 'Upload'}
          </button>
        </div>
      </div>
    </div>
  )
}

// ── LibraryCard ────────────────────────────────────────────────────────────

function LibraryCard({ lib }: { lib: AssetLibrary }) {
  const qc = useQueryClient()
  const [expanded, setExpanded] = useState(false)

  const refreshMut = useMutation({
    mutationFn: () => refreshAssetLibraryCatalog(lib.id),
    onSuccess: () => {
      toast.success('Catalog updated')
      qc.invalidateQueries({ queryKey: ['asset-libraries'] })
    },
    onError: (e: any) => toast.error(e.response?.data?.detail || 'Refresh failed'),
  })

  const toggleMut = useMutation({
    mutationFn: () => api.patch(`/asset-libraries/${lib.id}`, { is_active: !lib.is_active }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['asset-libraries'] })
    },
    onError: (e: any) => toast.error(e.response?.data?.detail || 'Toggle failed'),
  })

  const deleteMut = useMutation({
    mutationFn: () => deleteAssetLibrary(lib.id),
    onSuccess: () => {
      toast.success('Library deleted')
      qc.invalidateQueries({ queryKey: ['asset-libraries'] })
    },
    onError: (e: any) => toast.error(e.response?.data?.detail || 'Delete failed'),
  })

  const materialCount = lib.catalog?.materials?.length ?? 0
  const nodeGroupCount = lib.catalog?.node_groups?.length ?? 0
  const MAX_VISIBLE = 10

  return (
    <div className="card p-5 space-y-3">
      {/* Header row */}
      <div className="flex items-start justify-between gap-3">
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 flex-wrap">
            <h3 className="font-semibold text-content truncate">{lib.name}</h3>
            <span
              className={`text-xs px-2 py-0.5 rounded-full font-medium ${
                lib.is_active
                  ? 'bg-status-success-bg text-status-success-text'
                  : 'bg-surface-muted text-content-muted'
              }`}
            >
              {lib.is_active ? 'active' : 'inactive'}
            </span>
          </div>
          {lib.description && (
            <p className="text-sm text-content-muted mt-0.5">{lib.description}</p>
          )}
          {lib.original_filename && (
            <p className="text-xs text-content-muted font-mono mt-1">{lib.original_filename}</p>
          )}
        </div>

        {/* Actions */}
        <div className="flex items-center gap-2 shrink-0">
          {/* Active toggle */}
          <button
            onClick={() => toggleMut.mutate()}
            disabled={toggleMut.isPending}
            title={lib.is_active ? 'Deactivate' : 'Activate'}
            className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors focus:outline-none ${
              lib.is_active ? 'bg-green-500' : 'bg-gray-300'
            } disabled:opacity-50`}
          >
            <span
              className={`inline-block h-3.5 w-3.5 transform rounded-full bg-white shadow transition-transform ${
                lib.is_active ? 'translate-x-4' : 'translate-x-1'
              }`}
            />
          </button>

          <button
            onClick={() => refreshMut.mutate()}
            disabled={refreshMut.isPending}
            title="Refresh catalog"
            className="btn-icon text-content-muted hover:text-accent"
          >
            <RefreshCw size={15} className={refreshMut.isPending ? 'animate-spin' : ''} />
          </button>

          <button
            onClick={() => {
              if (confirm(`Delete "${lib.name}"? This cannot be undone.`)) {
                deleteMut.mutate()
              }
            }}
            disabled={deleteMut.isPending}
            title="Delete library"
            className="btn-icon text-content-muted hover:text-red-500"
          >
            <Trash2 size={15} />
          </button>
        </div>
      </div>

      {/* Catalog badges */}
      <div className="flex items-center gap-2 flex-wrap">
        <span className="text-xs px-2 py-0.5 rounded-full bg-accent-light text-accent font-medium">
          {materialCount} material{materialCount !== 1 ? 's' : ''}
        </span>
        {nodeGroupCount > 0 && (
          <span className="text-xs px-2 py-0.5 rounded-full bg-surface-muted text-content-muted font-medium">
            {nodeGroupCount} node group{nodeGroupCount !== 1 ? 's' : ''}
          </span>
        )}
      </div>

      {/* Expandable material list */}
      {materialCount > 0 && (
        <div>
          <button
            onClick={() => setExpanded((p) => !p)}
            className="flex items-center gap-1 text-xs text-content-secondary hover:text-content transition-colors"
          >
            {expanded ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
            {expanded ? 'Hide' : 'Show'} materials
          </button>
          {expanded && (
            <div className="mt-2 flex flex-wrap gap-1">
              {lib.catalog.materials.slice(0, MAX_VISIBLE).map((m) => {
                const name = typeof m === 'string' ? m : m.name
                return (
                  <span
                    key={name}
                    className="text-xs px-2 py-0.5 rounded bg-surface-alt border border-border-default text-content-secondary font-mono"
                  >
                    {name}
                  </span>
                )
              })}
              {materialCount > MAX_VISIBLE && (
                <span className="text-xs px-2 py-0.5 rounded bg-surface-muted text-content-muted">
                  ... and {materialCount - MAX_VISIBLE} more
                </span>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  )
}

// ── AssetLibraryPage ───────────────────────────────────────────────────────

export default function AssetLibraryPage() {
  const [showUpload, setShowUpload] = useState(false)

  const { data: libraries, isLoading, isError } = useQuery({
    queryKey: ['asset-libraries'],
    queryFn: listAssetLibraries,
  })

  return (
    <div className="p-8">
      {/* Header */}
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-content">Asset Libraries</h1>
          <p className="text-sm text-content-muted mt-1">
            Manage .blend material libraries used for Blender rendering.
          </p>
        </div>
        <button
          onClick={() => setShowUpload(true)}
          className="btn-primary"
        >
          <Upload size={16} />
          Upload Library
        </button>
      </div>

      {/* States */}
      {isLoading && (
        <div className="card p-12 text-center text-content-muted">
          <div className="animate-spin w-8 h-8 border-2 border-accent border-t-transparent rounded-full mx-auto mb-3" />
          Loading libraries...
        </div>
      )}

      {isError && (
        <div className="card p-8 text-center text-status-error-text">
          Failed to load asset libraries. Please try again.
        </div>
      )}

      {!isLoading && !isError && libraries && libraries.length === 0 && (
        <div className="card p-16 text-center">
          <Library size={44} className="text-content-muted mx-auto mb-3" />
          <p className="text-content-secondary font-medium">No asset libraries.</p>
          <p className="text-content-muted text-sm mt-1">
            Upload a .blend file to get started.
          </p>
          <button
            onClick={() => setShowUpload(true)}
            className="btn-primary mt-4"
          >
            <Upload size={16} />
            Upload Library
          </button>
        </div>
      )}

      {!isLoading && !isError && libraries && libraries.length > 0 && (
        <div className="space-y-4">
          {libraries.map((lib) => (
            <LibraryCard key={lib.id} lib={lib} />
          ))}
        </div>
      )}

      {showUpload && <UploadModal onClose={() => setShowUpload(false)} />}
    </div>
  )
}
