import Link from 'next/link'
import { createClient } from '@/lib/supabase/server'
import { getAppOrg } from '@/lib/org'
import { DeleteForm } from '@/components/delete-form'
import { fmtUsd } from '@/lib/format'
import { filterTeamsForViewAs, getEffectiveUser } from '@/lib/effective-user'
import { canTransfer } from '@/lib/permissions'
import { listVisibleTeams, type Team } from '@/lib/teams'
import {
  createTeamMember,
  deleteTeamMember,
  updateTeamMember,
} from './actions'

type TeamMember = {
  id: string
  team_id: string
  email: string
  display_name: string
  rate_proportion: number
  consolidate_as: string | null
  is_active: boolean
  notes: string | null
  /** Per-source-hour cost (USD). Post eliminate-proportion this is the
   * canonical cost basis — team.base_rate × rate_proportion is gone. */
  cost_rate_usd: number | string | null
  /** Owner-only USD/hr that Rian charges his client for this member's work. */
  billout_rate_usd: number | string | null
}

function formatPct(p: number): string {
  const v = p * 100
  return `${v % 1 === 0 ? v.toFixed(0) : v.toFixed(3)}%`
}

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

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

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

  // Load teams under the real JWT (RLS lets super-admin / org-owner see all),
  // then narrow to what the *effective* user would see when view-as is on.
  const eu = await getEffectiveUser(supabase, org.id)
  const allTeams = await listVisibleTeams(supabase, org.id)
  const teams = filterTeamsForViewAs(allTeams, eu)
  const teamIds = teams.map((t) => t.id)
  // Owner-only: who can see / edit per-member billout rates.
  const canSeeBillout = canTransfer(eu)

  const { data: members, error: queryError } = await supabase
    .from('team_members')
    .select(
      'id, team_id, email, display_name, rate_proportion, consolidate_as, is_active, notes, cost_rate_usd, billout_rate_usd',
    )
    .in('team_id', teamIds.length > 0 ? teamIds : ['00000000-0000-0000-0000-000000000000'])
    .order('is_active', { ascending: false })
    .order('display_name', { ascending: true })
    .returns<TeamMember[]>()

  const membersByTeam = new Map<string, TeamMember[]>()
  for (const m of members ?? []) {
    const list = membersByTeam.get(m.team_id) ?? []
    list.push(m)
    membersByTeam.set(m.team_id, list)
  }

  return (
    <main>
      <div className="page-head">
        <div>
          <h1>Teams</h1>
          <p className="subtitle">
            Cost rate and billout rate are per-source-hour. Cost is
            locked at import time — changing the rate later only affects
            new entries. Proportion only feeds the Toggl CSV export
            (legacy “converted hours” column); it no longer affects
            cost or billout.
          </p>
        </div>
      </div>

      {error && <p className="error">{error}</p>}
      {queryError && <p className="error">{queryError.message}</p>}

      {teams.length === 0 && (
        <p className="empty">
          No teams visible. Ask an org owner to create one for you.
        </p>
      )}

      {teams.map((team) => (
        <TeamPanel
          key={team.id}
          team={team}
          members={membersByTeam.get(team.id) ?? []}
          editId={editId ?? null}
          canSeeBillout={canSeeBillout}
        />
      ))}
    </main>
  )
}

function TeamPanel({
  team,
  members,
  editId,
  canSeeBillout,
}: {
  team: Team
  members: TeamMember[]
  editId: string | null
  /** Owner-only flag — gates the Billout rate column + the form input. */
  canSeeBillout: boolean
}) {
  const teamLabel = team.name || '(unnamed team)'
  // Only show the "Add member" form here if no row in this team is being edited.
  const editingHere = editId && members.some((m) => m.id === editId)

  return (
    <section style={{ marginBottom: '2rem' }}>
      <h2 style={{ margin: '0 0 0.75rem' }}>{teamLabel}</h2>

      {/* Base rate panel intentionally removed: post eliminate-proportion
          the team-wide base_rate is no longer used for cost or billout
          (each member has cost_rate_usd + billout_rate_usd directly).
          The column still exists in the DB but is vestigial. */}

      {!editingHere && (
        <div className="panel">
          <div className="panel-header">
            <h3 style={{ margin: 0, fontSize: '0.95rem' }}>
              Add team member to {teamLabel}
            </h3>
          </div>
          <form action={createTeamMember}>
            <input type="hidden" name="team_id" value={team.id} />
            <TeamMemberFields canSeeBillout={canSeeBillout} />
            <div className="flex-row" style={{ marginTop: '0.75rem' }}>
              <button type="submit">Add member</button>
            </div>
          </form>
        </div>
      )}

      <div className="panel" style={{ padding: 0, overflow: 'hidden' }}>
        <div
          style={{
            padding: '1rem 1.25rem 0.5rem',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          <h3 style={{ margin: 0, fontSize: '0.95rem' }}>
            Members <span className="muted">({members.length})</span>
          </h3>
        </div>

        {members.length > 0 ? (
          <div className="table-wrap" style={{ border: 'none', borderRadius: 0 }}>
            <table className="data">
              <thead>
                <tr>
                  <th>Email</th>
                  <th>Display name</th>
                  <th
                    className="num"
                    title="Per-source-hour cost. Locked onto each entry at import time."
                  >
                    Cost rate
                  </th>
                  {canSeeBillout && (
                    <th
                      className="num"
                      title="Owner-only: USD/hr Rian charges the client for this person's hours."
                    >
                      Billout rate
                    </th>
                  )}
                  <th
                    className="num"
                    title="Toggl-export only. Source hours × proportion = exported hours."
                  >
                    Proportion
                  </th>
                  <th>Consolidate as</th>
                  <th>Status</th>
                  <th>Notes</th>
                  <th />
                </tr>
              </thead>
              <tbody>
                {members.map((m) =>
                  m.id === editId ? (
                    <EditRow
                      key={m.id}
                      member={m}
                      canSeeBillout={canSeeBillout}
                    />
                  ) : (
                    <tr key={m.id}>
                      <td>{m.email}</td>
                      <td>{m.display_name}</td>
                      <td className="num">
                        {m.cost_rate_usd == null ? (
                          <span className="muted">—</span>
                        ) : (
                          fmtUsd(Number(m.cost_rate_usd))
                        )}
                      </td>
                      {canSeeBillout && (
                        <td className="num">
                          {m.billout_rate_usd == null ? (
                            <span className="muted">—</span>
                          ) : (
                            fmtUsd(Number(m.billout_rate_usd))
                          )}
                        </td>
                      )}
                      <td className="num">{formatPct(m.rate_proportion)}</td>
                      <td>
                        {m.consolidate_as ?? (
                          <span className="muted">(own name)</span>
                        )}
                      </td>
                      <td>
                        {m.is_active ? (
                          <span className="badge badge-ok">Active</span>
                        ) : (
                          <span className="badge badge-muted">Inactive</span>
                        )}
                      </td>
                      <td>
                        {m.notes ? (
                          <span className="muted" style={{ fontSize: '0.85em' }}>
                            {m.notes}
                          </span>
                        ) : null}
                      </td>
                      <td className="right">
                        <div
                          className="flex-row"
                          style={{ justifyContent: 'flex-end', gap: '0.75rem' }}
                        >
                          <Link href={`/team?edit=${m.id}`}>Edit</Link>
                          <DeleteForm
                            action={deleteTeamMember}
                            id={m.id}
                            confirmText={`Delete ${m.email}? This is permanent. Historical time entries referencing them will remain but lose the link.`}
                          />
                        </div>
                      </td>
                    </tr>
                  ),
                )}
              </tbody>
            </table>
          </div>
        ) : (
          <p className="empty">No members in this team yet.</p>
        )}
      </div>
    </section>
  )
}

function TeamMemberFields({
  defaults,
  canSeeBillout,
}: {
  defaults?: TeamMember
  /** Owner-only: gate the Billout rate input. */
  canSeeBillout: boolean
}) {
  const proportion = defaults?.rate_proportion ?? null
  const costDefault =
    defaults?.cost_rate_usd == null
      ? ''
      : Number(defaults.cost_rate_usd).toFixed(2)
  const billoutDefault =
    defaults?.billout_rate_usd == null
      ? ''
      : Number(defaults.billout_rate_usd).toFixed(2)

  return (
    <div
      style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(4, minmax(0, 1fr))',
        gap: '0.75rem 1rem',
      }}
    >
      <label>
        Email
        <input
          name="email"
          type="email"
          required
          autoComplete="off"
          defaultValue={defaults?.email}
        />
      </label>
      <label>
        Display name
        <input
          name="display_name"
          type="text"
          required
          defaultValue={defaults?.display_name}
        />
      </label>
      <label>
        Cost rate <span className="muted">(USD per source hour)</span>
        <input
          name="cost_rate_usd"
          type="number"
          step="0.01"
          min="0"
          placeholder="e.g. 7.00"
          defaultValue={costDefault}
        />
      </label>
      {canSeeBillout && (
        <label>
          Billout rate{' '}
          <span className="muted">(owner-only, USD per source hour)</span>
          <input
            name="billout_rate_usd"
            type="number"
            step="0.01"
            min="0"
            placeholder="e.g. 25.00"
            defaultValue={billoutDefault}
          />
        </label>
      )}
      <label>
        Proportion <span className="muted">(Toggl export only, 0–1 or 0–100%)</span>
        <input
          name="rate_proportion"
          type="text"
          required
          placeholder="0.5"
          defaultValue={proportion != null ? String(proportion) : ''}
        />
      </label>
      <label>
        Consolidate as <span className="muted">(blank = use own name)</span>
        <input
          name="consolidate_as"
          type="text"
          placeholder="Tingang"
          defaultValue={defaults?.consolidate_as ?? ''}
        />
      </label>
      <label style={{ gridColumn: 'span 2' }}>
        Notes <span className="muted">(optional)</span>
        <input
          name="notes"
          type="text"
          defaultValue={defaults?.notes ?? ''}
        />
      </label>
      <label
        style={{
          flexDirection: 'row',
          alignItems: 'center',
          gap: '0.5rem',
          alignSelf: 'end',
          paddingBottom: '0.5rem',
        }}
      >
        <input
          name="is_active"
          type="checkbox"
          defaultChecked={defaults ? defaults.is_active : true}
        />
        Active
      </label>
    </div>
  )
}

function EditRow({
  member,
  canSeeBillout,
}: {
  member: TeamMember
  canSeeBillout: boolean
}) {
  return (
    <tr style={{ background: '#fff8e1' }}>
      <td colSpan={canSeeBillout ? 9 : 8} style={{ padding: '1rem' }}>
        <form action={updateTeamMember}>
          <input type="hidden" name="id" value={member.id} />
          <TeamMemberFields
            defaults={member}
            canSeeBillout={canSeeBillout}
          />
          <div className="flex-row" style={{ marginTop: '0.75rem' }}>
            <button type="submit">Save</button>
            <Link href="/team" className="button-link-secondary">
              Cancel
            </Link>
          </div>
        </form>
      </td>
    </tr>
  )
}
