import { type FormEvent, useEffect, useMemo, useState } from 'react'
import { Link, useLocation, useParams, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import {
  fetchInventoryCreateForm,
  fetchInventoryItem,
  postInventoryItem,
  putInventoryItem,
} from '../../api/inventory'

const DEFAULT_CONDITIONS: Record<string, string> = {
  good: 'Good condition',
  needs_repair: 'Needs repair',
  need_replace: 'Need replace',
  cannot_find: 'Cannot find',
}

/** CI `inventory/classroom/form.php` */
export function InventoryClassroomFormPage() {
  const { itemId } = useParams()
  const { pathname } = useLocation()
  const [searchParams] = useSearchParams()
  const isCreate = pathname.endsWith('/create')

  const [categories, setCategories] = useState<Record<string, unknown>[]>([])
  const [conditionOptions, setConditionOptions] = useState<Record<string, string>>(DEFAULT_CONDITIONS)
  const [name, setName] = useState('')
  const [categoryId, setCategoryId] = useState('')
  const [condition, setCondition] = useState('')
  const [quantity, setQuantity] = useState('0')
  const [unit, setUnit] = useState('')
  const [sku, setSku] = useState('')
  const [description, setDescription] = useState('')
  const [updatedAt, setUpdatedAt] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const [onHand, setOnHand] = useState(0)
  const [needsRepairQty, setNeedsRepairQty] = useState(0)
  const [lossQty, setLossQty] = useState(0)
  const [missingQty, setMissingQty] = useState(0)

  useEffect(() => {
    let c = false
    setLoading(true)
    const run = isCreate
      ? fetchInventoryCreateForm('classroom', searchParams)
      : fetchInventoryItem(itemId ?? '')
    run
      .then((data) => {
        if (c) return
        if (data && typeof data === 'object') {
          const o = data as Record<string, unknown>
          const cats = Array.isArray(o.categories)
            ? (o.categories as Record<string, unknown>[])
            : []
          setCategories(cats)
          if (o.conditionOptions && typeof o.conditionOptions === 'object') {
            setConditionOptions(o.conditionOptions as Record<string, string>)
          }
          const item = (o.item ?? (isCreate ? {} : o)) as Record<string, unknown>
          if (!isCreate && item?.id != null) {
            setName(String(item.name ?? ''))
            setCategoryId(item.category_id != null ? String(item.category_id) : '')
            setCondition(String(item.condition ?? ''))
            const q = Number(item.quantity ?? 0)
            setQuantity(String(q))
            setOnHand(q)
            setNeedsRepairQty(Number(item.needs_repair_qty ?? 0))
            setLossQty(Number(item.need_replace_qty ?? 0))
            setMissingQty(Number(item.cannot_find_qty ?? 0))
            setUnit(String(item.unit ?? ''))
            setSku(String(item.sku ?? ''))
            setDescription(String(item.description ?? ''))
            setUpdatedAt(item.updated_at != null ? String(item.updated_at) : null)
          }
        }
        setError(null)
      })
      .catch((e: unknown) => {
        if (!c) setError(e instanceof ApiHttpError ? e.message : 'Unable to load form.')
      })
      .finally(() => {
        if (!c) setLoading(false)
      })
    return () => {
      c = true
    }
  }, [isCreate, itemId, searchParams])

  const goodCalc = useMemo(
    () => Math.max(0, onHand - needsRepairQty),
    [onHand, needsRepairQty],
  )

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setSaving(true)
    setError(null)
    const body: Record<string, unknown> = {
      type: 'classroom',
      name,
      category_id: categoryId === '' ? null : Number(categoryId),
      condition: condition || undefined,
      quantity: isCreate ? (quantity === '' ? 0 : Number(quantity)) : onHand,
      unit: unit || undefined,
      sku: sku || undefined,
      description: description || undefined,
    }
    try {
      if (isCreate) await postInventoryItem(body)
      else await putInventoryItem(itemId ?? '', body)
      window.location.href = '/app/administrator/inventory/classroom'
    } catch (err: unknown) {
      setError(err instanceof ApiHttpError ? err.message : 'Save failed.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="container my-4">
      <div className="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
        <h3 className="mb-0">{isCreate ? 'Add' : 'Edit'} Classroom Item</h3>
        {!isCreate && itemId ? (
          <div className="btn-group">
            <Link className="btn btn-sm btn-outline-secondary" to="/app/administrator/inventory/classroom">
              Items
            </Link>
            <Link
              className="btn btn-sm btn-outline-secondary"
              to={`/app/administrator/inventory/items/${itemId}/adjust`}
            >
              Adjust Stock
            </Link>
            <Link
              className="btn btn-sm btn-outline-secondary"
              to={`/app/administrator/inventory/classroom/${itemId}/audit`}
            >
              Audit
            </Link>
          </div>
        ) : null}
      </div>

      {error ? <div className="alert alert-danger">{error}</div> : null}
      {loading ? <p className="text-muted">Loading…</p> : null}

      {!loading ? (
        <>
          <form onSubmit={(ev) => void onSubmit(ev)}>
            <div className="row g-3">
              <div className="col-md-6">
                <label className="form-label">Name</label>
                <input
                  className="form-control"
                  required
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                />
              </div>
              <div className="col-md-6">
                <label className="form-label">Category</label>
                <select
                  className="form-select"
                  value={categoryId}
                  onChange={(e) => setCategoryId(e.target.value)}
                >
                  <option value="">— None —</option>
                  {categories.map((c) => (
                    <option key={String(c.id)} value={String(c.id)}>
                      {String(c.name ?? '')}
                    </option>
                  ))}
                </select>
              </div>

              <div className="col-md-4">
                <label className="form-label">Condition (overall)</label>
                <select
                  className="form-select"
                  value={condition}
                  onChange={(e) => setCondition(e.target.value)}
                >
                  <option value="">— Select —</option>
                  {Object.entries(conditionOptions).map(([val, label]) => (
                    <option key={val} value={val}>
                      {label}
                    </option>
                  ))}
                </select>
                <div className="form-text">Quick overall tag. Detailed states shown below.</div>
              </div>

              <div className="col-md-2">
                <label className="form-label">Quantity</label>
                <input
                  type="number"
                  min={0}
                  className="form-control"
                  value={isCreate ? quantity : String(onHand)}
                  onChange={(e) => {
                    if (isCreate) setQuantity(e.target.value)
                  }}
                  readOnly={!isCreate}
                />
                {!isCreate ? (
                  <div className="form-text">
                    Change on-hand via{' '}
                    <Link to={`/app/administrator/inventory/items/${itemId}/adjust`}>Adjust Stock</Link>.
                  </div>
                ) : null}
              </div>

              <div className="col-md-2">
                <label className="form-label">Unit</label>
                <input
                  className="form-control"
                  placeholder="pcs, set, box"
                  value={unit}
                  onChange={(e) => setUnit(e.target.value)}
                />
              </div>

              <div className="col-md-4">
                <label className="form-label">SKU</label>
                <input className="form-control" value={sku} onChange={(e) => setSku(e.target.value)} />
              </div>

              <div className="col-12">
                <label className="form-label">Description / Notes</label>
                <textarea
                  className="form-control"
                  rows={3}
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                />
              </div>
            </div>

            {!isCreate ? (
              <div className="card mt-4">
                <div className="card-header">Item State</div>
                <div className="card-body table-responsive">
                  <table className="table table-sm align-middle">
                    <thead className="table-light">
                      <tr>
                        <th>State</th>
                        <th className="text-end">Count</th>
                        <th>Included in On-Hand?</th>
                        <th>Notes</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr>
                        <td>
                          <strong>On Hand (now)</strong>
                        </td>
                        <td className="text-end">
                          <strong>{onHand}</strong>
                        </td>
                        <td>—</td>
                        <td>Sum of movements; authoritative stock.</td>
                      </tr>
                      <tr>
                        <td>Good</td>
                        <td className="text-end">{goodCalc}</td>
                        <td>Yes</td>
                        <td>Available to use (derived = On Hand − Needs Repair).</td>
                      </tr>
                      <tr>
                        <td>Needs Repair</td>
                        <td className="text-end">{needsRepairQty}</td>
                        <td>Yes</td>
                        <td>Unavailable until fixed.</td>
                      </tr>
                      <tr>
                        <td>Total Loss</td>
                        <td className="text-end">{lossQty}</td>
                        <td>No</td>
                        <td>Deducted via audit (Out).</td>
                      </tr>
                      <tr>
                        <td>Cannot Find</td>
                        <td className="text-end">{missingQty}</td>
                        <td>No</td>
                        <td>Deducted via audit (Out).</td>
                      </tr>
                    </tbody>
                    <tfoot>
                      <tr className="table-light">
                        <th>Available to Use</th>
                        <th className="text-end">{goodCalc}</th>
                        <th colSpan={2} />
                      </tr>
                      <tr className="table-light">
                        <th>Unavailable but On-Hand (Repair)</th>
                        <th className="text-end">{needsRepairQty}</th>
                        <th colSpan={2} />
                      </tr>
                      <tr className="table-light">
                        <th>Removed (Loss + Missing)</th>
                        <th className="text-end">{lossQty + missingQty}</th>
                        <th colSpan={2} />
                      </tr>
                    </tfoot>
                  </table>
                  <div className="small text-muted">
                    Update states via <strong>Audit</strong>; stock movements are created automatically.
                  </div>
                </div>
              </div>
            ) : null}

            <div className="mt-3 d-flex gap-2">
              <button type="submit" className="btn btn-primary" disabled={saving}>
                {saving ? 'Saving…' : isCreate ? 'Save' : 'Update'}
              </button>
              <Link className="btn btn-outline-secondary" to="/app/administrator/inventory/classroom">
                Cancel
              </Link>
            </div>
          </form>

          {!isCreate && updatedAt ? (
            <div className="text-muted mt-3">
              <small>Updated Date: {updatedAt}</small>
            </div>
          ) : null}
        </>
      ) : null}
    </div>
  )
}
