import Link from 'next/link'
import { createClient } from '@/lib/supabase/server'
import { getAppOrg } from '@/lib/org'
import { getEffectiveUser, getViewAsImportScope } from '@/lib/effective-user'
import { canManageImports } from '@/lib/permissions'
import { DeleteForm } from '@/components/delete-form'
import { deleteImportBatch } from './actions'
import { UploadForm } from './upload-form'

type Batch = {
  id: string
  name: string | null
  filename: string | null
  row_count: number
  imported_at: string
  notes: string | null
  total_entries: number
  transferred_entries: number
}

export default async function ImportPage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string; import_id?: string }>
}) {
  const { error, import_id } = await searchParams

  const supabase = await createClient()
  const org = await getAppOrg(supabase)

  if (!org) {
    return (
      <main>
        <div className="page-head">
          <h1>Import</h1>
        </div>
        <p className="error">Bowden Works organization not found.</p>
      </main>
    )
  }

  const eu = await getEffectiveUser(supabase, org.id)
  const canImport = canManageImports(eu)
  const viewAsScope = await getViewAsImportScope(supabase, org.id, eu)

  // Pull all batches (small dataset). For each, count entries + transferred entries.
  let rawBatchesQuery = supabase
    .from('clockify_imports')
    .select('id, name, filename, row_count, imported_at, notes')
    .eq('org_id', org.id)
    .order('imported_at', { ascending: false })
  if (viewAsScope) rawBatchesQuery = rawBatchesQuery.in('id', viewAsScope)
  const { data: rawBatches } = await rawBatchesQuery.returns<
    {
      id: string
      name: string | null
      filename: string | null
      row_count: number
      imported_at: string
      notes: string | null
    }[]
  >()

  const batches: Batch[] = []
  for (const b of rawBatches ?? []) {
    const [{ count: total }, { count: transferred }] = await Promise.all([
      supabase
        .from('time_entries')
        .select('id', { count: 'exact', head: true })
        .eq('org_id', org.id)
        .eq('import_id', b.id),
      supabase
        .from('time_entries')
        .select('id', { count: 'exact', head: true })
        .eq('org_id', org.id)
        .eq('import_id', b.id)
        .not('transferred_at', 'is', null),
    ])
    batches.push({
      ...b,
      total_entries: total ?? 0,
      transferred_entries: transferred ?? 0,
    })
  }

  let summary: {
    label: string
    matched: number
    unmatched: number
    unknownEmails: string[]
  } | null = null

  if (import_id) {
    const b = batches.find((x) => x.id === import_id)
    if (b) {
      const { data: entries } = await supabase
        .from('time_entries')
        .select('team_member_id, source_user_email')
        .eq('import_id', import_id)
        .eq('org_id', org.id)
        .returns<{ team_member_id: string | null; source_user_email: string }[]>()

      const matched = entries?.filter((e) => e.team_member_id).length ?? 0
      const unmatched = entries?.filter((e) => !e.team_member_id).length ?? 0
      const unknownEmails = Array.from(
        new Set(
          (entries ?? [])
            .filter((e) => !e.team_member_id && e.source_user_email)
            .map((e) => e.source_user_email),
        ),
      ).sort()

      summary = {
        label: b.name || b.filename || '(unnamed batch)',
        matched,
        unmatched,
        unknownEmails,
      }
    }
  }

  return (
    <main>
      <div className="page-head">
        <div>
          <h1>Import</h1>
          <p className="subtitle">
            Each upload is a named batch. You can delete a batch later, as
            long as none of its entries have been transferred yet.
          </p>
        </div>
      </div>

      {error && <p className="error">{error}</p>}

      {summary && (
        <div className="panel" style={{ background: '#f0fdf4', borderColor: '#bbf7d0' }}>
          <h2 style={{ marginTop: 0 }}>Import complete</h2>
          <p style={{ marginTop: 0 }}>
            Batch <strong>{summary.label}</strong> imported.{' '}
            {summary.matched + summary.unmatched} entries in total.
          </p>
          <div className="stat-row">
            <div className="stat">
              <span className="stat-label">Matched</span>
              <span className="stat-value">{summary.matched}</span>
            </div>
            <div className="stat">
              <span className="stat-label">Unmatched</span>
              <span
                className={`stat-value ${summary.unmatched > 0 ? 'under-target' : ''}`}
              >
                {summary.unmatched}
              </span>
            </div>
          </div>
          {summary.unknownEmails.length > 0 && (
            <div className="warning" style={{ marginTop: '1rem' }}>
              <strong>Unknown emails:</strong>{' '}
              {summary.unknownEmails.join(', ')}
              <br />
              These entries are imported but can&apos;t transfer until you{' '}
              <Link href="/team">add the team members</Link>. After adding, you
              can edit those entries on the <Link href="/entries">Entries</Link>{' '}
              page to re-resolve them.
            </div>
          )}
          <p style={{ marginTop: '1rem' }}>
            <Link href={`/entries?batch=${import_id}`}>
              View entries in this batch →
            </Link>
          </p>
        </div>
      )}

      {canImport && (
        <div className="panel">
          <h2 style={{ marginTop: 0 }}>Upload time-tracking CSV</h2>
          <p className="muted" style={{ margin: '0.25rem 0 0', fontSize: '0.9em' }}>
            Pick the source so the right date / time defaults are applied
            and the batch is tagged for the export pipeline.
          </p>
          <UploadForm />
        </div>
      )}

      <div className="panel" style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ padding: '1rem 1.25rem 0.5rem' }}>
          <h2 style={{ margin: 0, fontSize: '1.05rem' }}>
            Import batches{' '}
            <span className="muted">({batches.length})</span>
          </h2>
        </div>
        {batches.length === 0 ? (
          <p className="empty">No batches yet.</p>
        ) : (
          <div className="table-wrap" style={{ border: 'none', borderRadius: 0 }}>
            <table className="data">
              <thead>
                <tr>
                  <th>Name</th>
                  <th>File</th>
                  <th>Imported</th>
                  <th className="num">Entries</th>
                  <th className="num">Transferred</th>
                  <th>Notes</th>
                  <th />
                </tr>
              </thead>
              <tbody>
                {batches.map((b) => (
                  <tr key={b.id}>
                    <td>
                      <Link href={`/entries?batch=${b.id}`}>
                        {b.name || (
                          <span className="muted">(unnamed)</span>
                        )}
                      </Link>
                    </td>
                    <td>
                      {b.filename ? (
                        <span className="muted" style={{ fontSize: '0.85em' }}>
                          {b.filename}
                        </span>
                      ) : (
                        <span className="muted">—</span>
                      )}
                    </td>
                    <td>
                      {new Date(b.imported_at).toLocaleString()}
                    </td>
                    <td className="num">{b.total_entries}</td>
                    <td className="num">{b.transferred_entries}</td>
                    <td>
                      {b.notes ? (
                        <span className="muted" style={{ fontSize: '0.85em' }}>
                          {b.notes}
                        </span>
                      ) : null}
                    </td>
                    <td className="right">
                      {canImport ? (
                        b.transferred_entries > 0 ? (
                          <span
                            className="muted"
                            title={`Can't delete — ${b.transferred_entries} entries already transferred.`}
                            style={{ fontSize: '0.85em' }}
                          >
                            Locked
                          </span>
                        ) : (
                          <DeleteForm
                            action={deleteImportBatch}
                            id={b.id}
                            confirmText={`Delete batch "${b.name || b.filename || '(unnamed)'}" and all ${b.total_entries} entries in it? This cannot be undone.`}
                          />
                        )
                      ) : null}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </main>
  )
}
