import { useEffect, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { FileStack, FileText, Pencil, Plus, Settings as SettingsIcon, Trash2 } from 'lucide-react'
import { ConfirmDeleteModal } from '../components/ConfirmDeleteModal'
import { Modal } from '../components/Modal'
import { isEmptyRichText, richTextToPlain } from '../components/RichTextEditor'
import { useToast } from '../context/ToastContext'
import { ApiError, isAbortError } from '../lib/api'
import {
  createInvoiceItemTemplate,
  deleteInvoiceItemTemplate,
  deleteInvoiceTemplate,
  listInvoiceItemTemplates,
  listInvoiceTemplates,
  updateInvoiceItemTemplate,
} from '../services/invoiceService'
import type { InvoiceItemTemplate, InvoiceTemplate } from '../types/invoice'
import { formatIrtInput, formatIrtPrice, parseIrtInput } from '../utils/irtPrice'
import pageStyles from '../components/PageContent.module.css'
import tableStyles from './BusinessesPage.module.css'
import styles from './SettingsPage.module.css'

type ItemDraft = {
  title: string
  duration: string
  worktime: string
  description: string
  price: string
  discountedPrice: string
}

const EMPTY_ITEM_DRAFT: ItemDraft = {
  title: '',
  duration: '',
  worktime: '',
  description: '',
  price: '',
  discountedPrice: '',
}

function itemDraftFromTemplate(t: InvoiceItemTemplate): ItemDraft {
  return {
    title: t.title,
    duration: t.duration ?? '',
    worktime: t.worktime ?? '',
    description: t.description ?? '',
    price: formatIrtInput(String(Math.round(t.price))),
    discountedPrice:
      t.discountedPrice === null || t.discountedPrice === undefined
        ? ''
        : formatIrtInput(String(Math.round(t.discountedPrice))),
  }
}

function itemDraftToPayload(draft: ItemDraft) {
  const price = parseIrtInput(draft.price)
  if (!draft.title.trim()) throw new Error('Title is required.')
  if (price === null) throw new Error('Price is required.')
  const discountedPrice = draft.discountedPrice.trim()
    ? parseIrtInput(draft.discountedPrice)
    : null
  if (draft.discountedPrice.trim() && discountedPrice === null) {
    throw new Error('Discounted price is invalid.')
  }
  if (discountedPrice !== null && discountedPrice > price) {
    throw new Error('Discounted price cannot exceed price.')
  }
  return {
    title: draft.title.trim(),
    duration: draft.duration.trim() || undefined,
    worktime: draft.worktime.trim() || undefined,
    description: draft.description.trim() || undefined,
    price,
    discountedPrice,
  }
}

export function SettingsPage() {
  const navigate = useNavigate()
  const { showToast } = useToast()
  const [itemTemplates, setItemTemplates] = useState<InvoiceItemTemplate[]>([])
  const [invoiceTemplates, setInvoiceTemplates] = useState<InvoiceTemplate[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  const [itemEditorOpen, setItemEditorOpen] = useState(false)
  const [editingItem, setEditingItem] = useState<InvoiceItemTemplate | null>(null)
  const [itemDraft, setItemDraft] = useState<ItemDraft>(EMPTY_ITEM_DRAFT)
  const [itemSubmitting, setItemSubmitting] = useState(false)
  const [itemFormError, setItemFormError] = useState('')
  const [removeItemTarget, setRemoveItemTarget] = useState<InvoiceItemTemplate | null>(null)
  const [removeTplTarget, setRemoveTplTarget] = useState<InvoiceTemplate | null>(null)

  async function reload(signal?: AbortSignal) {
    setLoading(true)
    setError('')
    try {
      const [items, templates] = await Promise.all([
        listInvoiceItemTemplates(signal),
        listInvoiceTemplates(signal),
      ])
      setItemTemplates(items.items)
      setInvoiceTemplates(templates.items)
    } catch (err) {
      if (isAbortError(err)) return
      setError(err instanceof ApiError ? err.message : 'Unable to load invoice settings.')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    const controller = new AbortController()
    void reload(controller.signal)
    return () => controller.abort()
  }, [])

  function openCreateItem() {
    setEditingItem(null)
    setItemDraft(EMPTY_ITEM_DRAFT)
    setItemFormError('')
    setItemEditorOpen(true)
  }

  function openEditItem(template: InvoiceItemTemplate) {
    setEditingItem(template)
    setItemDraft(itemDraftFromTemplate(template))
    setItemFormError('')
    setItemEditorOpen(true)
  }

  async function handleSaveItem() {
    setItemFormError('')
    let payload
    try {
      payload = itemDraftToPayload(itemDraft)
    } catch (err) {
      setItemFormError(err instanceof Error ? err.message : 'Invalid form.')
      return
    }
    setItemSubmitting(true)
    try {
      if (editingItem) {
        await updateInvoiceItemTemplate(editingItem.id, payload)
        showToast('Item template updated.', 'success')
      } else {
        await createInvoiceItemTemplate(payload)
        showToast('Item template created.', 'success')
      }
      setItemEditorOpen(false)
      await reload()
    } catch (err) {
      setItemFormError(err instanceof ApiError ? err.message : 'Unable to save item template.')
    } finally {
      setItemSubmitting(false)
    }
  }

  async function handleRemoveItem() {
    if (!removeItemTarget) return
    try {
      await deleteInvoiceItemTemplate(removeItemTarget.id)
      showToast('Item template removed.', 'success')
      setRemoveItemTarget(null)
      await reload()
    } catch (err) {
      showToast(err instanceof ApiError ? err.message : 'Unable to remove item.', 'error')
    }
  }

  async function handleRemoveTpl() {
    if (!removeTplTarget) return
    try {
      await deleteInvoiceTemplate(removeTplTarget.id)
      showToast('Invoice template removed.', 'success')
      setRemoveTplTarget(null)
      await reload()
    } catch (err) {
      showToast(err instanceof ApiError ? err.message : 'Unable to remove template.', 'error')
    }
  }

  return (
    <main className={pageStyles.content}>
      <div className={pageStyles.pageHeader}>
        <div>
          <h2 className={pageStyles.pageTitle}>Settings</h2>
          <p className={pageStyles.pageSubtitle}>
            Platform configuration used across Meshkee super admin tools.
          </p>
        </div>
      </div>

      {error ? <p className={styles.alertError}>{error}</p> : null}

      <section className={styles.section}>
        <div className={styles.sectionHeader}>
          <div className={styles.sectionTitleRow}>
            <FileStack size={18} />
            <div>
              <h3 className={styles.sectionTitle}>Invoice templates</h3>
              <p className={styles.sectionSubtitle}>
                Full blueprints (name, top text, items, key points, bank accounts) used when issuing
                invoices to businesses. Pick one and edit, or start blank.
              </p>
            </div>
          </div>
          <button
            type="button"
            className={`${tableStyles.btn} ${tableStyles.btnPrimary}`}
            onClick={() => navigate('/settings/invoice-templates/new')}
          >
            <Plus size={16} />
            Add template
          </button>
        </div>

        <div className={tableStyles.tableWrap}>
          <div className={tableStyles.tableHeader}>
            <div className={tableStyles.tableHeaderTitle}>Templates</div>
            <div className={tableStyles.meta}>
              {loading
                ? 'Loading…'
                : `${invoiceTemplates.length} template${invoiceTemplates.length === 1 ? '' : 's'}`}
            </div>
          </div>
          <table className={tableStyles.table}>
            <thead>
              <tr>
                <th className={tableStyles.th}>Name</th>
                <th className={tableStyles.th}>Items</th>
                <th className={tableStyles.th}>Key points</th>
                <th className={tableStyles.th}>Accounts</th>
                <th className={`${tableStyles.th} ${tableStyles.thActions}`}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {!loading && invoiceTemplates.length === 0 ? (
                <tr>
                  <td className={tableStyles.td} colSpan={5}>
                    <div className={styles.emptyState}>
                      <SettingsIcon size={20} />
                      <span>No invoice templates yet. Add one to speed up issuing invoices.</span>
                    </div>
                  </td>
                </tr>
              ) : null}
              {invoiceTemplates.map((template) => (
                <tr key={template.id}>
                  <td className={tableStyles.td}>
                    <div className={styles.itemTitle}>{template.name}</div>
                    {template.topText && !isEmptyRichText(template.topText) ? (
                      <div className={`${tableStyles.subText} ${styles.topTextPreview}`} title={richTextToPlain(template.topText)}>
                        {richTextToPlain(template.topText)}
                      </div>
                    ) : null}
                  </td>
                  <td className={tableStyles.td}>{template.items.length}</td>
                  <td className={tableStyles.td}>{template.keyPoints.length}</td>
                  <td className={tableStyles.td}>{template.accounts.length}</td>
                  <td className={`${tableStyles.td} ${tableStyles.tdActions}`}>
                    <div className={tableStyles.rowActions}>
                      <button
                        type="button"
                        className={tableStyles.controlBtn}
                        onClick={() => navigate(`/settings/invoice-templates/${template.id}`)}
                        title="Edit"
                        aria-label="Edit"
                      >
                        <Pencil size={16} />
                      </button>
                      <button
                        type="button"
                        className={`${tableStyles.controlBtn} ${tableStyles.controlBtnDanger}`}
                        onClick={() => setRemoveTplTarget(template)}
                        title="Remove"
                        aria-label="Remove"
                      >
                        <Trash2 size={16} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>

      <section className={`${styles.section} ${styles.sectionSpaced}`}>
        <div className={styles.sectionHeader}>
          <div className={styles.sectionTitleRow}>
            <FileText size={18} />
            <div>
              <h3 className={styles.sectionTitle}>Invoice item templates</h3>
              <p className={styles.sectionSubtitle}>
                Reusable line items you can drop into invoice templates or when issuing an invoice.
              </p>
            </div>
          </div>
          <button
            type="button"
            className={`${tableStyles.btn} ${tableStyles.btnPrimary}`}
            onClick={openCreateItem}
          >
            <Plus size={16} />
            Add item
          </button>
        </div>

        <div className={tableStyles.tableWrap}>
          <div className={tableStyles.tableHeader}>
            <div className={tableStyles.tableHeaderTitle}>Predefined line items</div>
            <div className={tableStyles.meta}>
              {loading
                ? 'Loading…'
                : `${itemTemplates.length} item${itemTemplates.length === 1 ? '' : 's'}`}
            </div>
          </div>
          <table className={tableStyles.table}>
            <thead>
              <tr>
                <th className={tableStyles.th}>Title</th>
                <th className={tableStyles.th}>Duration</th>
                <th className={tableStyles.th}>Worktime</th>
                <th className={tableStyles.th}>Price</th>
                <th className={tableStyles.th}>Discounted</th>
                <th className={`${tableStyles.th} ${tableStyles.thActions}`}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {!loading && itemTemplates.length === 0 ? (
                <tr>
                  <td className={tableStyles.td} colSpan={6}>
                    <div className={styles.emptyState}>
                      <SettingsIcon size={20} />
                      <span>No predefined items yet.</span>
                    </div>
                  </td>
                </tr>
              ) : null}
              {itemTemplates.map((template) => (
                <tr key={template.id}>
                  <td className={tableStyles.td}>
                    <div className={styles.itemTitle}>{template.title}</div>
                    {template.description ? (
                      <div className={tableStyles.subText}>{template.description}</div>
                    ) : null}
                  </td>
                  <td className={tableStyles.td}>{template.duration || '—'}</td>
                  <td className={tableStyles.td}>{template.worktime || '—'}</td>
                  <td className={tableStyles.td}>{formatIrtPrice(template.price)}</td>
                  <td className={tableStyles.td}>
                    {template.discountedPrice === null
                      ? '—'
                      : formatIrtPrice(template.discountedPrice)}
                  </td>
                  <td className={`${tableStyles.td} ${tableStyles.tdActions}`}>
                    <div className={tableStyles.rowActions}>
                      <button
                        type="button"
                        className={tableStyles.controlBtn}
                        onClick={() => openEditItem(template)}
                        title="Edit"
                        aria-label="Edit"
                      >
                        <Pencil size={16} />
                      </button>
                      <button
                        type="button"
                        className={`${tableStyles.controlBtn} ${tableStyles.controlBtnDanger}`}
                        onClick={() => setRemoveItemTarget(template)}
                        title="Remove"
                        aria-label="Remove"
                      >
                        <Trash2 size={16} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>

      <p className={styles.hint}>
        Tip: open a business from <Link to="/businesses">Businesses</Link> to issue an invoice from a
        template or from scratch.
      </p>

      <Modal
        open={itemEditorOpen}
        title={editingItem ? 'Edit item template' : 'Add item template'}
        onClose={() => !itemSubmitting && setItemEditorOpen(false)}
        wide
      >
        <div className={styles.formGrid}>
          <div className={`${tableStyles.field} ${styles.span2}`}>
            <label htmlFor="item-title">Title</label>
            <input
              id="item-title"
              value={itemDraft.title}
              onChange={(e) => setItemDraft((d) => ({ ...d, title: e.target.value }))}
              placeholder="e.g. Website setup"
            />
          </div>
          <div className={tableStyles.field}>
            <label htmlFor="item-duration">Duration</label>
            <input
              id="item-duration"
              value={itemDraft.duration}
              onChange={(e) => setItemDraft((d) => ({ ...d, duration: e.target.value }))}
              placeholder="e.g. 3 months"
            />
          </div>
          <div className={tableStyles.field}>
            <label htmlFor="item-worktime">Worktime</label>
            <input
              id="item-worktime"
              value={itemDraft.worktime}
              onChange={(e) => setItemDraft((d) => ({ ...d, worktime: e.target.value }))}
              placeholder="e.g. 40 hours"
            />
          </div>
          <div className={tableStyles.field}>
            <label htmlFor="item-price">Price (IRT)</label>
            <input
              id="item-price"
              inputMode="numeric"
              value={itemDraft.price}
              onChange={(e) =>
                setItemDraft((d) => ({ ...d, price: formatIrtInput(e.target.value) }))
              }
              placeholder="0"
            />
          </div>
          <div className={tableStyles.field}>
            <label htmlFor="item-discount">Discounted price (IRT)</label>
            <input
              id="item-discount"
              inputMode="numeric"
              value={itemDraft.discountedPrice}
              onChange={(e) =>
                setItemDraft((d) => ({ ...d, discountedPrice: formatIrtInput(e.target.value) }))
              }
              placeholder="Optional"
            />
          </div>
          <div className={`${tableStyles.field} ${styles.span2}`}>
            <label htmlFor="item-desc">Description</label>
            <textarea
              id="item-desc"
              rows={3}
              value={itemDraft.description}
              onChange={(e) => setItemDraft((d) => ({ ...d, description: e.target.value }))}
              placeholder="Optional details"
            />
          </div>
        </div>
        {itemFormError ? <p className={styles.alertError}>{itemFormError}</p> : null}
        <div className={tableStyles.actionsRow}>
          <button
            type="button"
            className={`${tableStyles.btn} ${tableStyles.btnGhost}`}
            onClick={() => setItemEditorOpen(false)}
            disabled={itemSubmitting}
          >
            Cancel
          </button>
          <button
            type="button"
            className={`${tableStyles.btn} ${tableStyles.btnPrimary}`}
            onClick={() => void handleSaveItem()}
            disabled={itemSubmitting}
          >
            {itemSubmitting ? 'Saving…' : editingItem ? 'Save changes' : 'Create item'}
          </button>
        </div>
      </Modal>

      <ConfirmDeleteModal
        open={!!removeTplTarget}
        title="Remove invoice template"
        message={
          removeTplTarget
            ? `Remove “${removeTplTarget.name}” from invoice templates?`
            : ''
        }
        onCancel={() => setRemoveTplTarget(null)}
        onConfirm={() => void handleRemoveTpl()}
      />

      <ConfirmDeleteModal
        open={!!removeItemTarget}
        title="Remove item template"
        message={
          removeItemTarget
            ? `Remove “${removeItemTarget.title}” from predefined line items?`
            : ''
        }
        onCancel={() => setRemoveItemTarget(null)}
        onConfirm={() => void handleRemoveItem()}
      />
    </main>
  )
}
