import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Pencil, Trash2, Plus, Check, X } from 'lucide-react'
import { toast } from 'sonner'
import { listPricingTiers, createPricingTier, updatePricingTier, deletePricingTier } from '../../api/pricing'
import type { PricingTier } from '../../api/pricing'

const EMPTY_FORM = { category_key: '', quality_level: 'Normal', price_per_item: '', description: '' }

export default function PricingTierTable() {
  const qc = useQueryClient()
  const [showAdd, setShowAdd] = useState(false)
  const [form, setForm] = useState(EMPTY_FORM)
  const [editingId, setEditingId] = useState<number | null>(null)
  const [editDraft, setEditDraft] = useState<Partial<PricingTier>>({})

  const { data: tiers, isLoading } = useQuery({
    queryKey: ['pricing-tiers'],
    queryFn: listPricingTiers,
  })

  const createMut = useMutation({
    mutationFn: () =>
      createPricingTier({
        category_key: form.category_key.trim(),
        quality_level: form.quality_level.trim() || 'Normal',
        price_per_item: parseFloat(form.price_per_item),
        description: form.description.trim() || undefined,
      }),
    onSuccess: () => {
      toast.success('Pricing tier created')
      qc.invalidateQueries({ queryKey: ['pricing-tiers'] })
      setForm(EMPTY_FORM)
      setShowAdd(false)
    },
    onError: (e: any) => toast.error(e.response?.data?.detail || 'Failed to create tier'),
  })

  const updateMut = useMutation({
    mutationFn: ({ id, data }: { id: number; data: Partial<PricingTier> }) =>
      updatePricingTier(id, {
        category_key: data.category_key,
        quality_level: data.quality_level,
        price_per_item: data.price_per_item != null ? Number(data.price_per_item) : undefined,
        description: data.description !== undefined ? data.description ?? undefined : undefined,
        is_active: data.is_active,
      }),
    onSuccess: () => {
      toast.success('Tier updated')
      qc.invalidateQueries({ queryKey: ['pricing-tiers'] })
      setEditingId(null)
      setEditDraft({})
    },
    onError: (e: any) => toast.error(e.response?.data?.detail || 'Failed to update tier'),
  })

  const deleteMut = useMutation({
    mutationFn: (id: number) => deletePricingTier(id),
    onSuccess: () => {
      toast.success('Tier deleted')
      qc.invalidateQueries({ queryKey: ['pricing-tiers'] })
    },
    onError: (e: any) => toast.error(e.response?.data?.detail || 'Failed to delete tier'),
  })

  function startEdit(tier: PricingTier) {
    setEditingId(tier.id)
    setEditDraft({
      category_key: tier.category_key,
      quality_level: tier.quality_level,
      price_per_item: tier.price_per_item,
      description: tier.description ?? '',
      is_active: tier.is_active,
    })
  }

  function cancelEdit() {
    setEditingId(null)
    setEditDraft({})
  }

  const canCreate = form.category_key.trim() !== '' && form.price_per_item !== '' && !isNaN(parseFloat(form.price_per_item))

  return (
    <div>
      {/* Add form toggle */}
      <div className="p-4 border-b border-border-light">
        {showAdd ? (
          <div className="space-y-3">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-2">
              <input
                placeholder="Category key (e.g. TRB)"
                value={form.category_key}
                onChange={(e) => setForm({ ...form, category_key: e.target.value })}
                className="input-base"
                title="Product category key this tier applies to (e.g. TRB, Kugellager). Leave empty for the global fallback tier."
              />
              <input
                placeholder="Quality level (e.g. Normal)"
                value={form.quality_level}
                onChange={(e) => setForm({ ...form, quality_level: e.target.value })}
                className="input-base"
                title="Quality level label for this tier (e.g. Normal, Premium). Used for display purposes."
              />
              <input
                placeholder="€ / item"
                type="number"
                step="0.01"
                min="0"
                value={form.price_per_item}
                onChange={(e) => setForm({ ...form, price_per_item: e.target.value })}
                className="input-base"
              />
              <input
                placeholder="Description (optional)"
                value={form.description}
                onChange={(e) => setForm({ ...form, description: e.target.value })}
                className="input-base"
              />
            </div>
            <div className="flex gap-2">
              <button
                onClick={() => createMut.mutate()}
                disabled={!canCreate || createMut.isPending}
                className="btn-primary text-sm"
              >
                {createMut.isPending ? 'Saving…' : 'Add Tier'}
              </button>
              <button onClick={() => { setShowAdd(false); setForm(EMPTY_FORM) }} className="btn-secondary text-sm">
                Cancel
              </button>
            </div>
          </div>
        ) : (
          <button onClick={() => setShowAdd(true)} className="btn-primary text-sm">
            <Plus size={14} />
            Add New Tier
          </button>
        )}
      </div>

      {/* Table */}
      {isLoading ? (
        <div className="p-6 text-center text-content-muted text-sm">Loading…</div>
      ) : !tiers || tiers.length === 0 ? (
        <div className="p-6 text-center text-content-muted text-sm">
          No pricing tiers configured. Add one above.
        </div>
      ) : (
        <div className="overflow-x-auto">
          {/* Warning if no default tier */}
          {!tiers.some((t) => t.category_key === 'default') && (
            <div className="mx-4 mt-3 mb-1 px-3 py-2 rounded-lg bg-status-warning-bg border border-border-default text-status-warning-text text-xs">
              No global default tier configured. Orders without a category-specific tier will have no price.
            </div>
          )}
          <table className="w-full text-sm">
            <thead className="bg-surface-alt border-b border-border-default">
              <tr>
                <th className="text-left px-4 py-2 font-medium text-content-secondary">Category</th>
                <th className="text-left px-4 py-2 font-medium text-content-secondary">Quality Level</th>
                <th className="text-right px-4 py-2 font-medium text-content-secondary">€ / Item</th>
                <th className="text-left px-4 py-2 font-medium text-content-secondary">Description</th>
                <th className="text-center px-4 py-2 font-medium text-content-secondary">Active</th>
                <th className="px-4 py-2" />
              </tr>
            </thead>
            <tbody className="divide-y divide-border-light">
              {[...tiers].sort((a, b) => {
                // Sort 'default' to top
                if (a.category_key === 'default' && b.category_key !== 'default') return -1
                if (b.category_key === 'default' && a.category_key !== 'default') return 1
                return 0
              }).map((tier) => {
                const isEditing = editingId === tier.id
                const isDefault = tier.category_key === 'default'
                return (
                  <tr key={tier.id} className={`hover:bg-surface-hover transition-colors ${isDefault ? 'bg-status-warning-bg' : ''}`}>
                    <td className="px-4 py-2 font-mono font-medium text-content">
                      {isEditing ? (
                        <input
                          type="text"
                          value={editDraft.category_key ?? tier.category_key}
                          onChange={(e) => setEditDraft((d) => ({ ...d, category_key: e.target.value }))}
                          className="w-full px-2 py-1 border border-border-default rounded text-sm focus:outline-none focus:border-accent"
                        />
                      ) : (
                        <div className="flex items-center gap-2">
                          {tier.category_key}
                          {isDefault && (
                            <span className="text-xs px-1.5 py-0.5 rounded bg-status-warning-bg text-status-warning-text font-medium font-sans" title="This is the global fallback pricing tier — used when no category-specific tier matches. The 'default' category key identifies this tier.">
                              Global Fallback
                            </span>
                          )}
                        </div>
                      )}
                    </td>
                    <td className="px-4 py-2 text-content-secondary">
                      {isEditing ? (
                        <input
                          type="text"
                          value={editDraft.quality_level ?? tier.quality_level}
                          onChange={(e) => setEditDraft((d) => ({ ...d, quality_level: e.target.value }))}
                          className="w-full px-2 py-1 border border-border-default rounded text-sm focus:outline-none focus:border-accent"
                        />
                      ) : (
                        tier.quality_level
                      )}
                    </td>
                    <td className="px-4 py-2 text-right">
                      {isEditing ? (
                        <input
                          type="number"
                          step="0.01"
                          min="0"
                          value={editDraft.price_per_item ?? tier.price_per_item}
                          onChange={(e) => setEditDraft((d) => ({ ...d, price_per_item: parseFloat(e.target.value) }))}
                          className="w-24 px-2 py-1 border border-border-default rounded text-sm text-right focus:outline-none focus:border-accent"
                        />
                      ) : (
                        <span className="font-medium">€ {Number(tier.price_per_item).toFixed(2)}</span>
                      )}
                    </td>
                    <td className="px-4 py-2 text-content-muted">
                      {isEditing ? (
                        <input
                          type="text"
                          value={editDraft.description ?? tier.description ?? ''}
                          onChange={(e) => setEditDraft((d) => ({ ...d, description: e.target.value }))}
                          className="w-full px-2 py-1 border border-border-default rounded text-sm focus:outline-none focus:border-accent"
                        />
                      ) : (
                        tier.description || <span className="text-content-muted">—</span>
                      )}
                    </td>
                    <td className="px-4 py-2 text-center">
                      {isEditing ? (
                        <input
                          type="checkbox"
                          checked={editDraft.is_active ?? tier.is_active}
                          onChange={(e) => setEditDraft((d) => ({ ...d, is_active: e.target.checked }))}
                          className="w-4 h-4"
                        />
                      ) : (
                        <span className={`badge ${tier.is_active ? 'badge-green' : 'badge-gray'}`}>
                          {tier.is_active ? 'yes' : 'no'}
                        </span>
                      )}
                    </td>
                    <td className="px-4 py-2">
                      <div className="flex items-center justify-end gap-1">
                        {isEditing ? (
                          <>
                            <button
                              onClick={() => updateMut.mutate({ id: tier.id, data: editDraft })}
                              disabled={updateMut.isPending}
                              className="p-1 text-status-success-text hover:bg-surface-hover rounded"
                              title="Save"
                            >
                              <Check size={15} />
                            </button>
                            <button
                              onClick={cancelEdit}
                              className="p-1 text-content-muted hover:bg-surface-muted rounded"
                              title="Cancel"
                            >
                              <X size={15} />
                            </button>
                          </>
                        ) : (
                          <>
                            <button
                              onClick={() => startEdit(tier)}
                              className="p-1 text-content-muted hover:text-accent hover:bg-surface-hover rounded"
                              title="Edit"
                            >
                              <Pencil size={14} />
                            </button>
                            <button
                              onClick={() => { if (confirm(`Delete ${tier.category_key} / ${tier.quality_level}?`)) deleteMut.mutate(tier.id) }}
                              className="p-1 text-content-muted hover:text-red-500 hover:bg-red-50 rounded"
                              title="Delete"
                            >
                              <Trash2 size={14} />
                            </button>
                          </>
                        )}
                      </div>
                    </td>
                  </tr>
                )
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}
