"use client"

import { Plus, Trash2 } from "lucide-react"

export type OverviewColumns = string[]
export type OverviewRow = string[]
export interface OverviewTableData {
  title?: string
  columns: OverviewColumns
  rows: OverviewRow[]
}

interface OverviewSectionProps {
  value: OverviewTableData | null
  onChange: (value: OverviewTableData | null) => void
}

const HEADER_COUNT = 1
const EMPTY_COLUMNS: OverviewColumns = ["Label"]
const EMPTY_ROW = (len: number): OverviewRow => Array.from({ length: len }).map(() => "") as OverviewRow

export function OverviewSection({ value, onChange }: OverviewSectionProps) {
  const table = value
  const columns = table?.columns ?? EMPTY_COLUMNS
  const rows = table?.rows ?? []
  const headersReady = columns.length > 0 && columns.every((c) => c.trim() !== "")
  const headerColumns = (() => {
    const base = columns.slice(0, HEADER_COUNT)
    if (base.length < HEADER_COUNT) return [...base, ...Array(HEADER_COUNT - base.length).fill("")]
    return base
  })()
  const extraColumns = columns.slice(HEADER_COUNT)

  function enableOverview() {
    onChange({
      title: "",
      columns: [...EMPTY_COLUMNS] as OverviewColumns,
      rows: [],
    })
  }

  function disableOverview() {
    onChange(null)
  }

  function updateHeader(index: number, val: string) {
    if (!table) return
    const nextColumns = [...(table.columns ?? [])] as OverviewColumns
    // ensure length to index
    while (nextColumns.length <= index) nextColumns.push("")
    nextColumns[index] = val
    onChange({ ...table, columns: nextColumns })
  }

  function addRow() {
    if (!table) return
    onChange({
      ...table,
      rows: [...table.rows, EMPTY_ROW(table.columns.length)],
    })
  }

  function removeRow(index: number) {
    if (!table) return
    onChange({
      ...table,
      rows: table.rows.filter((_, i) => i !== index),
    })
  }

  function updateCell(rowIndex: number, colIndex: number, val: string) {
    if (!table) return
    const nextRows = table.rows.map((row, i) => {
      if (i !== rowIndex) return row
      const updated = [...row] as OverviewRow
      updated[colIndex] = val
      return updated
    })
    onChange({ ...table, rows: nextRows })
  }

  function addColumn() {
    if (!table) return
    const nextCols = [...table.columns, ""]
    const nextRows = table.rows.map((r) => [...r, ""])
    onChange({ ...table, columns: nextCols, rows: nextRows })
  }

  function removeColumn(index: number) {
    if (!table) return
    // Prevent removing required header columns
    if (index < HEADER_COUNT) return
    if (table.columns.length <= HEADER_COUNT) return
    const nextCols = table.columns.filter((_, i) => i !== index)
    const nextRows = table.rows.map((r) => r.filter((_, i) => i !== index))
    onChange({ ...table, columns: nextCols, rows: nextRows })
  }

  return (
    <div className="flex flex-col gap-3">
      <div className="flex flex-col gap-1.5">
        <label className="text-xs font-bold text-foreground font-sans uppercase tracking-wider">Overview Title</label>
        <input
          type="text"
          value={table?.title ?? ""}
          onChange={(e) => {
            const v = e.target.value
            if (!table) {
              // if overview not yet enabled, enable it with the typed title
              onChange({
                title: v,
                columns: [...EMPTY_COLUMNS] as OverviewColumns,
                rows: [],
              })
              return
            }
            onChange({ ...table, title: v })
          }}
          placeholder="e.g. Key Metrics"
          className="bg-card border border-border rounded-xl px-3 py-2 text-sm text-foreground font-sans placeholder:text-muted-foreground outline-none focus:ring-2 focus:ring-[#2BB673]/30 focus:border-[#2BB673] transition-colors"
        />
      </div>
      <div className="flex items-center justify-between">
        <label className="text-xs font-bold text-foreground font-sans uppercase tracking-wider">
          Overview
        </label>
        {table ? (
          <button
            type="button"
            onClick={disableOverview}
            className="flex items-center cursor-pointer gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold font-sans transition-all hover:brightness-105 active:scale-[0.98]"
            style={{ background: "rgba(239,68,68,0.10)", color: "#ef4444" }}
          >
            Disable Overview
          </button>
        ) : (
          <button
            type="button"
            onClick={enableOverview}
            className="flex items-center cursor-pointer gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold font-sans transition-all hover:brightness-105 active:scale-[0.98]"
            style={{ background: "rgba(43,182,115,0.10)", color: "var(--brand-green)" }}
          >
            <Plus className="w-3.5 h-3.5" aria-hidden="true" />
            Enable Overview
          </button>
        )}
      </div>

      {!table ? (
        <div
          className="flex flex-col items-center justify-center gap-2 py-8 rounded-xl border border-dashed"
          style={{ borderColor: "var(--border)" }}
        >
          <p className="text-xs text-muted-foreground font-sans">
            Overview is optional. Enable it to build a flexible table with any number of columns.
          </p>
          <button
            type="button"
            onClick={enableOverview}
            className="text-xs cursor-pointer font-semibold font-sans"
            style={{ color: "var(--brand-green)" }}
          >
            Enable Overview
          </button>
        </div>
      ) : (
        <div className="flex flex-col gap-4">
          <div className="flex flex-wrap gap-2 items-center">
            {headerColumns.map((col, index) => (
              <div key={`header-${index}`} className="flex items-center gap-2">
                <input
                  type="text"
                  value={col}
                  onChange={(e) => updateHeader(index, e.target.value)}
                  placeholder={`Column ${index + 1} title`}
                  className="bg-card border border-border rounded-xl px-3 py-2 text-sm text-foreground font-sans placeholder:text-muted-foreground outline-none focus:ring-2 focus:ring-[#2BB673]/30 focus:border-[#2BB673] transition-colors"
                  aria-label={`Overview column ${index + 1} title`}
                />
              </div>
            ))}
            {extraColumns.map((col, i) => {
              const index = HEADER_COUNT + i
              return (
                <div key={`extra-${index}`} className="flex items-center gap-2">
                  <input
                    type="text"
                    value={col}
                    onChange={(e) => updateHeader(index, e.target.value)}
                    placeholder={`Extra Column ${i + 1} title`}
                    className="bg-card border border-border rounded-xl px-3 py-2 text-sm text-foreground font-sans placeholder:text-muted-foreground outline-none focus:ring-2 focus:ring-[#2BB673]/30 focus:border-[#2BB673] transition-colors"
                    aria-label={`Overview extra column ${i + 1} title`}
                  />
                  <button
                    type="button"
                    onClick={() => removeColumn(index)}
                    className="p-1 rounded-md text-muted-foreground hover:text-red-500 hover:bg-red-50 transition-colors"
                    aria-label={`Remove extra column ${i + 1}`}
                  >
                    <Trash2 className="w-4 h-4" aria-hidden="true" />
                  </button>
                </div>
              )
            })}
            <button
              type="button"
              onClick={addColumn}
              className="flex items-center cursor-pointer gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold font-sans transition-all hover:brightness-105 active:scale-[0.98]"
              style={{ background: "rgba(43,182,115,0.10)", color: "var(--brand-green)" }}
            >
              <Plus className="w-3.5 h-3.5" aria-hidden="true" />
              Add Column
            </button>
          </div>

          <p className="text-xs text-muted-foreground font-sans">
            Edit any cell directly. Add rows even if some column titles are empty.
          </p>

          <div className="overflow-x-auto rounded-xl border border-border">
            <table
              className="w-full border-collapse"
              style={{ minWidth: `${Math.max(420, columns.length * 160)}px` }}
            >
              <thead>
                <tr className="bg-muted/40">
                  {columns.map((col, index) => (
                    <th
                      key={`th-${index}`}
                      className="border-b border-border px-3 py-2 text-left text-xs font-bold text-foreground font-sans"
                    >
                      {col.trim() || `Column ${index + 1}`}
                    </th>
                  ))}
                  <th className="border-b border-border px-3 py-2 text-right text-xs font-bold text-foreground font-sans">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody>
                {rows.length === 0 ? (
                  <tr>
                    <td
                      colSpan={columns.length + 1}
                      className="px-3 py-5 text-center text-xs text-muted-foreground font-sans"
                    >
                      No rows yet. Add your first row.
                    </td>
                  </tr>
                ) : (
                  rows.map((row, rowIndex) => (
                    <tr key={`row-${rowIndex}`} className="align-top">
                      {row.map((cell, colIndex) => (
                        <td key={`cell-${rowIndex}-${colIndex}`} className="border-t border-border p-0">
                          <input
                            type="text"
                            value={cell}
                            onChange={(e) => updateCell(rowIndex, colIndex, e.target.value)}
                            className="w-full bg-transparent px-3 py-2 text-sm text-foreground font-sans outline-none focus:bg-accent/30"
                            aria-label={`Overview row ${rowIndex + 1} column ${colIndex + 1}`}
                          />
                        </td>
                      ))}
                      <td className="border-t border-border px-2 py-1 text-right">
                        <button
                          type="button"
                          onClick={() => removeRow(rowIndex)}
                          className="p-2 cursor-pointer rounded-lg text-muted-foreground hover:text-red-500 hover:bg-red-50 transition-colors"
                          aria-label={`Remove overview row ${rowIndex + 1}`}
                        >
                          <Trash2 className="w-4 h-4" aria-hidden="true" />
                        </button>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>

          <div className="flex items-center justify-between gap-2">
            <p className="text-xs text-muted-foreground font-sans">
              Excel-style input: edit any cell directly.
            </p>
            <button
              type="button"
              onClick={addRow}
              className="flex items-center cursor-pointer gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold font-sans transition-all hover:brightness-105 active:scale-[0.98]"
              style={{ background: "rgba(43,182,115,0.10)", color: "var(--brand-green)" }}
            >
              <Plus className="w-3.5 h-3.5" aria-hidden="true" />
              Add Row
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
