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

const ALL_CATEGORIES = [
  { key: 'default', label: 'default (Global Fallback)' },
  { key: 'TRB', label: 'TRB' },
  { key: 'Kugellager', label: 'Kugellager' },
  { key: 'CRB', label: 'CRB' },
  { key: 'Gleitlager', label: 'Gleitlager' },
  { key: 'SRB_TORB', label: 'SRB/TORB' },
  { key: 'Linear_schiene', label: 'Linear' },
  { key: 'Anschlagplatten', label: 'Anschlag' },
]

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

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> & { _price_str?: string }>({})

  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,
        is_active: form.is_active,
      }),
    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> & { _price_str?: string } }) => {
      const { _price_str, ...rest } = data
      return updatePricingTier(id, {
        category_key: rest.category_key,
        quality_level: rest.quality_level,
        price_per_item: rest.price_per_item != null ? Number(rest.price_per_item) : undefined,
        description: rest.description !== undefined ? rest.description ?? undefined : undefined,
        is_active: rest.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,
      _price_str: String(tier.price_per_item),
    })
  }

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

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

  /* Shared edit form grid — used by both edit-row and add-row */
  function renderEditFormGrid(mode: 'add' | 'edit', tier: PricingTier | null) {
    const catVal = mode === 'edit' ? (editDraft.category_key ?? tier?.category_key ?? '') : form.category_key
    const qualVal = mode === 'edit' ? (editDraft.quality_level ?? tier?.quality_level ?? '') : form.quality_level
    const priceVal = mode === 'edit' ? (editDraft._price_str ?? String(tier?.price_per_item ?? '')) : form.price_per_item
    const descVal = mode === 'edit' ? (editDraft.description ?? tier?.description ?? '') : form.description
    const activeVal = mode === 'edit' ? (editDraft.is_active ?? tier?.is_active ?? true) : form.is_active

    const setCat = (v: string) => mode === 'edit' ? setEditDraft((d) => ({ ...d, category_key: v })) : setForm((f) => ({ ...f, category_key: v }))
    const setQual = (v: string) => mode === 'edit' ? setEditDraft((d) => ({ ...d, quality_level: v })) : setForm((f) => ({ ...f, quality_level: v }))
    const setPrice = (v: string) => {
      if (mode === 'edit') {
        setEditDraft((d) => ({ ...d, _price_str: v, price_per_item: v ? parseFloat(v) : undefined }))
      } else {
        setForm((f) => ({ ...f, price_per_item: v }))
      }
    }
    const setDesc = (v: string) => mode === 'edit' ? setEditDraft((d) => ({ ...d, description: v })) : setForm((f) => ({ ...f, description: v }))
    const setActive = (v: boolean) => mode === 'edit' ? setEditDraft((d) => ({ ...d, is_active: v })) : setForm((f) => ({ ...f, is_active: v }))

    return (
      <div className="space-y-4">
        {/* Row 1: Category Key, Quality Level, Price per Item */}
        <div className="grid grid-cols-3 gap-4">
          <div>
            <label className="block text-xs font-medium text-content-secondary mb-1">Category Key</label>
            <select
              value={catVal}
              onChange={(e) => setCat(e.target.value)}
              className="input-base w-full"
            >
              <option value="">-- Select category --</option>
              {ALL_CATEGORIES.map((c) => (
                <option key={c.key} value={c.key}>{c.label}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-xs font-medium text-content-secondary mb-1">Quality Level</label>
            <input
              type="text"
              value={qualVal}
              onChange={(e) => setQual(e.target.value)}
              placeholder="e.g. Normal, Premium"
              className="input-base w-full"
            />
          </div>
          <div>
            <label className="block text-xs font-medium text-content-secondary mb-1">Price per Item</label>
            <div className="relative">
              <span className="absolute left-2.5 top-1/2 -translate-y-1/2 text-content-muted text-sm pointer-events-none">&#8364;</span>
              <input
                type="number"
                step="0.01"
                min="0"
                value={priceVal}
                onChange={(e) => setPrice(e.target.value)}
                placeholder="0.00"
                className="input-base w-full pl-7"
              />
            </div>
          </div>
        </div>

        {/* Row 2: Description (full width) */}
        <div>
          <label className="block text-xs font-medium text-content-secondary mb-1">Description</label>
          <textarea
            value={descVal}
            onChange={(e) => setDesc(e.target.value)}
            placeholder="Optional description for this pricing tier"
            rows={2}
            className="input-base w-full resize-y"
          />
        </div>

        {/* Row 3: Active checkbox + Save/Cancel */}
        <div className="flex items-center justify-between pt-2 border-t border-border-light">
          <label className="flex items-center gap-2 text-sm text-content-secondary cursor-pointer">
            <input
              type="checkbox"
              checked={activeVal}
              onChange={(e) => setActive(e.target.checked)}
              className="w-4 h-4"
            />
            Active
          </label>
          <div className="flex gap-2">
            <button
              className="btn-secondary text-sm"
              onClick={() => {
                if (mode === 'edit') {
                  cancelEdit()
                } else {
                  setShowAdd(false)
                  setForm(EMPTY_FORM)
                }
              }}
            >
              Cancel
            </button>
            <button
              className="btn-primary text-sm"
              disabled={mode === 'add' ? (!canCreate || createMut.isPending) : updateMut.isPending}
              onClick={() => {
                if (mode === 'add') {
                  createMut.mutate()
                } else if (tier) {
                  updateMut.mutate({ id: tier.id, data: editDraft })
                }
              }}
            >
              {mode === 'add'
                ? (createMut.isPending ? 'Saving...' : 'Add Tier')
                : (updateMut.isPending ? 'Saving...' : 'Save Changes')
              }
            </button>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div>
      {/* Add tier toggle button */}
      <div className="p-4 border-b border-border-light">
        <button
          onClick={() => { setShowAdd(!showAdd); if (!showAdd) setForm(EMPTY_FORM) }}
          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="overflow-x-auto">
          <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">&#8364; / 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>
              {/* Add new — expandable form */}
              {showAdd && (
                <tr className="border-b border-border-light bg-status-success-bg">
                  <td colSpan={6} className="px-6 py-5 border-l-4 border-status-success-text">
                    <div className="text-sm font-medium text-content-secondary mb-3">New Pricing Tier</div>
                    {renderEditFormGrid('add', null)}
                  </td>
                </tr>
              )}
              <tr>
                <td colSpan={6} className="p-6 text-center text-content-muted text-sm">
                  No pricing tiers configured. Add one above.
                </td>
              </tr>
            </tbody>
          </table>
        </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">&#8364; / 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">
              {/* Add new — expandable form */}
              {showAdd && (
                <tr className="border-b border-border-light bg-status-success-bg">
                  <td colSpan={6} className="px-6 py-5 border-l-4 border-status-success-text">
                    <div className="text-sm font-medium text-content-secondary mb-3">New Pricing Tier</div>
                    {renderEditFormGrid('add', null)}
                  </td>
                </tr>
              )}

              {[...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 (
                  <React.Fragment key={tier.id}>
                    {/* Display row — always visible */}
                    <tr className={`hover:bg-surface-hover transition-colors ${isDefault ? 'bg-status-warning-bg' : ''} ${isEditing ? 'bg-surface-hover' : ''}`}>
                      <td className="px-4 py-2 font-mono font-medium text-content">
                        <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">
                        {tier.quality_level}
                      </td>
                      <td className="px-4 py-2 text-right">
                        <span className="font-medium">&#8364; {Number(tier.price_per_item).toFixed(2)}</span>
                      </td>
                      <td className="px-4 py-2 text-content-muted">
                        {tier.description || <span className="text-content-muted">—</span>}
                      </td>
                      <td className="px-4 py-2 text-center">
                        <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">
                          <button
                            onClick={() => {
                              if (isEditing) {
                                cancelEdit()
                              } else {
                                startEdit(tier)
                              }
                            }}
                            className="p-1 text-content-muted hover:text-accent hover:bg-surface-hover rounded"
                            title={isEditing ? 'Collapse edit form' : '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>

                    {/* Expandable edit form row */}
                    {isEditing && (
                      <tr>
                        <td colSpan={6} className="px-6 py-5 bg-surface-alt border-l-4 border-accent border-b-2 border-b-border-light">
                          {renderEditFormGrid('edit', tier)}
                        </td>
                      </tr>
                    )}
                  </React.Fragment>
                )
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}
