import Link from 'next/link'
import { createClient } from '@/lib/supabase/server'
import { getAppOrg } from '@/lib/org'
import { getEffectiveUser } from '@/lib/effective-user'
import { canTransfer } from '@/lib/permissions'
import { SearchableCombobox } from '@/components/searchable-combobox'
import { DeleteForm } from '@/components/delete-form'
import {
  createAutoRule,
  createHighlightKeyword,
  deleteAutoRule,
  deleteHighlightKeyword,
  updateAutoRule,
} from './actions'

type HighlightRow = { id: string; keyword: string; created_at: string }
type AutoRuleRow = {
  id: string
  keyword: string
  project_id: string
  assignment_description: string | null
  category: string | null
  created_at: string
  project: {
    name: string
    client: { name: string } | null
  } | null
}

export default async function CcExpensesRulesPage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string; info?: string; edit?: string }>
}) {
  const sp = await searchParams
  const supabase = await createClient()
  const org = await getAppOrg(supabase)
  if (!org) {
    return (
      <main>
        <h1>Rules</h1>
        <p className="error">Bowden Works organization not found.</p>
      </main>
    )
  }
  const eu = await getEffectiveUser(supabase, org.id)
  if (!canTransfer(eu)) {
    return (
      <main>
        <h1>Rules</h1>
        <p className="error">Owner only.</p>
      </main>
    )
  }

  const editId = typeof sp.edit === 'string' ? sp.edit : null

  const [{ data: highlights }, { data: rules }, { data: projects }] =
    await Promise.all([
      supabase
        .from('cc_highlight_keywords')
        .select('id, keyword, created_at')
        .eq('org_id', org.id)
        .order('keyword')
        .returns<HighlightRow[]>(),
      supabase
        .from('cc_auto_rules')
        .select(
          'id, keyword, project_id, assignment_description, category, created_at, project:projects(name, client:clients(name))',
        )
        .eq('org_id', org.id)
        .order('created_at', { ascending: false })
        .returns<AutoRuleRow[]>(),
      supabase
        .from('projects')
        .select('id, name, client:clients(name)')
        .eq('org_id', org.id)
        .order('name')
        .returns<
          { id: string; name: string; client: { name: string } | null }[]
        >(),
    ])

  const projectOptions = (projects ?? [])
    .filter((p) => p.client?.name)
    .map((p) => ({ id: p.id, label: `${p.client!.name} : ${p.name}` }))
    .sort((a, b) => a.label.localeCompare(b.label))

  // Distinct categories from existing rules (autocomplete source).
  const categoryOptions = Array.from(
    new Set(
      (rules ?? [])
        .map((r) => r.category)
        .filter((c): c is string => !!c),
    ),
  ).sort()
  const categoryListId = 'cc-rule-cats'

  return (
    <main>
      <div className="page-head">
        <div>
          <p className="muted" style={{ fontSize: '0.85em', margin: 0 }}>
            <Link href="/tools/cc-expenses">← Batches</Link>
          </p>
          <h1 style={{ margin: '0.1rem 0' }}>CC Expense Rules</h1>
          <p className="subtitle">
            <strong>Highlight keywords</strong> paint matching lines
            yellow so you don&apos;t skip them.{' '}
            <strong>Auto-assign rules</strong> pre-fill (project,
            description, category) on matching lines at paste time.
            Both apply ONLY to newly-pasted lines — existing lines
            aren&apos;t retroactively touched.
          </p>
        </div>
      </div>

      {sp.error && <p className="error">{sp.error}</p>}
      {sp.info && <p className="info">{sp.info}</p>}

      <datalist id={categoryListId}>
        {categoryOptions.map((c) => (
          <option key={c} value={c} />
        ))}
      </datalist>

      {/* ------------------- Highlight keywords ------------------- */}
      <div
        className="panel"
        style={{ padding: 0, overflow: 'hidden', marginBottom: '1.25rem' }}
      >
        <div className="panel-header">
          <h2 style={{ margin: 0, fontSize: '1.05rem' }}>
            Highlight keywords
          </h2>
        </div>
        <div style={{ padding: '0.75rem 1rem', borderBottom: '1px solid #eee' }}>
          <form action={createHighlightKeyword}>
            <div
              style={{
                display: 'grid',
                gridTemplateColumns: '1fr auto',
                gap: '0.5rem',
                alignItems: 'end',
              }}
            >
              <label style={{ fontSize: '0.85em' }}>
                New keyword{' '}
                <span className="muted">
                  (case-insensitive substring match against the line
                  description)
                </span>
                <input
                  type="text"
                  name="keyword"
                  placeholder="e.g. UBER"
                  required
                  autoFocus
                />
              </label>
              <button type="submit">Add</button>
            </div>
          </form>
        </div>
        {highlights && highlights.length > 0 ? (
          <table className="data">
            <thead>
              <tr>
                <th>Keyword</th>
                <th>Added</th>
                <th />
              </tr>
            </thead>
            <tbody>
              {highlights.map((h) => (
                <tr
                  key={h.id}
                  style={{ background: '#fefce8' /* hint at the row color */ }}
                >
                  <td style={{ fontFamily: 'monospace' }}>{h.keyword}</td>
                  <td className="muted" style={{ fontSize: '0.85em' }}>
                    {h.created_at.slice(0, 10)}
                  </td>
                  <td className="right">
                    <DeleteForm
                      action={deleteHighlightKeyword}
                      id={h.id}
                      confirmText={`Delete highlight keyword "${h.keyword}"?`}
                    />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <p className="empty" style={{ padding: '1rem', margin: 0 }}>
            No highlight keywords yet.
          </p>
        )}
      </div>

      {/* ------------------- Auto-assign rules ------------------- */}
      <div className="panel" style={{ padding: 0, overflow: 'hidden' }}>
        <div className="panel-header">
          <h2 style={{ margin: 0, fontSize: '1.05rem' }}>
            Auto-assign rules
          </h2>
        </div>
        <div style={{ padding: '0.75rem 1rem', borderBottom: '1px solid #eee' }}>
          <form action={createAutoRule}>
            <div
              style={{
                display: 'grid',
                gridTemplateColumns: '1.2fr 1.5fr 1fr 1fr auto',
                gap: '0.5rem',
                alignItems: 'end',
              }}
            >
              <label style={{ fontSize: '0.85em' }}>
                Keyword
                <input
                  type="text"
                  name="keyword"
                  required
                  placeholder="e.g. ADS9772464823"
                />
              </label>
              <label style={{ fontSize: '0.85em' }}>
                Project{' '}
                <span className="muted">({'{client}'} : {'{project}'})</span>
                <SearchableCombobox
                  name="project_id"
                  options={projectOptions}
                  placeholder="search projects…"
                />
              </label>
              <label style={{ fontSize: '0.85em' }}>
                Description
                <input
                  type="text"
                  name="assignment_description"
                  placeholder="e.g. Google"
                />
              </label>
              <label style={{ fontSize: '0.85em' }}>
                Category
                <input
                  type="text"
                  name="category"
                  list={categoryListId}
                  placeholder="e.g. Client Advertising Spend"
                />
              </label>
              <button type="submit">Add rule</button>
            </div>
          </form>
        </div>
        {rules && rules.length > 0 ? (
          <table className="data">
            <thead>
              <tr>
                <th>Keyword</th>
                <th>Project</th>
                <th>Description</th>
                <th>Category</th>
                <th />
              </tr>
            </thead>
            <tbody>
              {rules.map((r) =>
                editId === r.id ? (
                  <tr key={r.id} style={{ background: '#fff8e1' }}>
                    <td colSpan={5} style={{ padding: '0.6rem 1rem' }}>
                      <form action={updateAutoRule}>
                        <input type="hidden" name="id" value={r.id} />
                        <div
                          style={{
                            display: 'grid',
                            gridTemplateColumns: '1.2fr 1.5fr 1fr 1fr auto auto',
                            gap: '0.5rem',
                            alignItems: 'end',
                          }}
                        >
                          <label style={{ fontSize: '0.85em' }}>
                            Keyword
                            <input
                              type="text"
                              name="keyword"
                              defaultValue={r.keyword}
                              required
                            />
                          </label>
                          <label style={{ fontSize: '0.85em' }}>
                            Project
                            <SearchableCombobox
                              name="project_id"
                              options={projectOptions}
                              defaultId={r.project_id}
                            />
                          </label>
                          <label style={{ fontSize: '0.85em' }}>
                            Description
                            <input
                              type="text"
                              name="assignment_description"
                              defaultValue={r.assignment_description ?? ''}
                            />
                          </label>
                          <label style={{ fontSize: '0.85em' }}>
                            Category
                            <input
                              type="text"
                              name="category"
                              list={categoryListId}
                              defaultValue={r.category ?? ''}
                            />
                          </label>
                          <button type="submit">Save</button>
                          <Link
                            href="/tools/cc-expenses/rules"
                            className="button-link-secondary"
                          >
                            Cancel
                          </Link>
                        </div>
                      </form>
                    </td>
                  </tr>
                ) : (
                  <tr key={r.id}>
                    <td style={{ fontFamily: 'monospace' }}>{r.keyword}</td>
                    <td>
                      {r.project?.client?.name && r.project?.name
                        ? `${r.project.client.name} : ${r.project.name}`
                        : <span className="muted">— (deleted?)</span>}
                    </td>
                    <td>
                      {r.assignment_description ?? (
                        <span className="muted">—</span>
                      )}
                    </td>
                    <td>{r.category ?? <span className="muted">—</span>}</td>
                    <td className="right">
                      <div
                        className="flex-row"
                        style={{ justifyContent: 'flex-end', gap: '0.75rem' }}
                      >
                        <Link
                          href={`/tools/cc-expenses/rules?edit=${r.id}`}
                          scroll={false}
                        >
                          Edit
                        </Link>
                        <DeleteForm
                          action={deleteAutoRule}
                          id={r.id}
                          confirmText={`Delete rule for "${r.keyword}"?`}
                        />
                      </div>
                    </td>
                  </tr>
                ),
              )}
            </tbody>
          </table>
        ) : (
          <p className="empty" style={{ padding: '1rem', margin: 0 }}>
            No auto-assign rules yet.
          </p>
        )}
      </div>
    </main>
  )
}
