'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { CompanyAccessCard } from '@/app/settings/company-access-card'
import { CompanyConsole, CompanyPreviewContext, type MemberView } from './company-console'
import { companyRoleLabel } from '@/lib/domain/company'
import { formatFullDate } from '@/lib/format'
import {
  PREVIEW_APPROVALS, PREVIEW_AUDIT, PREVIEW_CARRIER, PREVIEW_COMPANY, PREVIEW_MEMBERS,
  previewClaim, previewMembership,
} from '@/lib/demo/company-preview'
import type {
  BrokerPage, Company, CompanyAuditEvent, CompanyClaim, CompanyMembership, UserRole,
} from '@/types/db'

/**
 * The Company page — every state of "how you get connected to your company",
 * on one screen (Task 83, 2026-09-08).
 *
 * Nash: "I tried to open my corporate profile… it's not doing anything… Can
 * we have the design done so we can present to the team before we do the
 * backend? Can we have the flow of how to request a verification, how you get
 * connected? If I'm logged in with an email that is the email of the company
 * that has a pending request — should I have an approve or deny ability? If
 * my email is not linked to a company, what buttons do I have?"
 *
 * Four situations, always reachable through the "view as" bar (same pattern
 * as the dashboard's pilot preview and /billing's preview states):
 *   new        — not connected: explains the three steps and offers the button
 *   pending    — request sent: status, resend, different MC number
 *   approvals  — you ARE the corporate contact: approve / deny / report
 *   agent/admin — approved member: the corporate profile (read-only / editable)
 * The real state is the default. Preview states run on demo data and never
 * write anything — including when migration 0013 is not applied yet.
 */

export type CompanyView = 'new' | 'pending' | 'approvals' | 'agent' | 'admin'

export interface AwaitingApprovalView {
  claim: CompanyClaim
  company: Company
  requester: { name: string; email: string; phone: string | null }
}

export function CompanyHome({
  available,
  me,
  company,
  membership,
  claim,
  members,
  audit,
  brokerPage,
  approvals,
  internal = false,
}: {
  available: boolean
  me: { email: string; name: string; role: UserRole }
  /**
   * Internal staff see the state switcher (Task 96). Nash, naming this exact
   * bar: "if I go to the Broker, under Profile, I go to Company. Design
   * preview, right? … It's for admin and developers only. Nobody else should
   * see it." A customer sees only their own real state.
   */
  internal?: boolean
  company: Company | null
  membership: CompanyMembership | null
  claim: CompanyClaim | null
  members: MemberView[]
  audit: CompanyAuditEvent[]
  brokerPage: BrokerPage | null
  /** Requests waiting for THIS person as the corporate contact. */
  approvals: AwaitingApprovalView[]
}) {
  const approved = !!company && membership?.status === 'approved'
  const pendingClaim =
    !approved &&
    !!claim &&
    ['pending_corporate_approval', 'company_verification_pending', 'admin_review_required'].includes(claim.claim_status)
  const realView: CompanyView = approved
    ? membership!.role === 'company_owner' || membership!.role === 'company_admin'
      ? 'admin'
      : 'agent'
    : approvals.length > 0
      ? 'approvals'
      : pendingClaim
        ? 'pending'
        : 'new'

  // A customer is pinned to their real state; only internal staff may switch.
  const [chosenView, setChosenView] = useState<CompanyView>(realView)
  const view = internal ? chosenView : realView
  const setView = setChosenView
  const preview = view !== realView || !available
  const isCarrier = me.role === 'dispatcher'
  const demoCompany = isCarrier ? PREVIEW_CARRIER : PREVIEW_COMPANY

  const views: Array<[CompanyView, string]> = [
    ['new', 'Not connected'],
    ['pending', 'Request pending'],
    ['approvals', 'Approvals for you'],
    ['agent', 'Approved agent'],
    ['admin', 'Company admin'],
  ]

  return (
    <CompanyPreviewContext.Provider value={preview}>
      <div className="mt-3 flex flex-wrap items-center justify-between gap-3">
        <h1 className="text-2xl font-bold tracking-tight">Company</h1>
      </div>

      {/* Pilot design preview — walk every state of the flow on demo data.
          Internal only (Task 96). */}
      {internal && (
      <div className="mt-3 rounded-xl border border-amber-300 bg-amber-50 px-4 py-2.5 text-xs text-amber-900">
        <span className="font-semibold">Design preview — view as:</span>
        {views.map(([key, label]) => (
          <button
            key={key}
            type="button"
            onClick={() => setView(key)}
            className={`ml-1.5 rounded-full px-2.5 py-0.5 font-semibold ${
              view === key ? 'bg-amber-900 text-white' : 'bg-white/70 hover:bg-white'
            }`}
          >
            {label}
            {key === realView ? ' (you)' : ''}
          </button>
        ))}
        <span className="mt-1 block text-[11px] text-amber-800/80">
          {!available
            ? 'The company database is not connected yet, so every state runs on demo data and nothing is saved.'
            : preview
              ? 'Demo data — nothing you do in a preview state is saved. Your real state is marked "(you)".'
              : 'This is your real state. Switch to see how the other states look.'}
        </span>
      </div>
      )}

      {view === 'new' && (
        <NotConnected
          me={me}
          isCarrier={isCarrier}
          available={available}
          preview={preview}
          claim={preview ? null : claim}
          company={preview ? null : company}
          membership={preview ? null : membership}
        />
      )}

      {view === 'pending' && (
        <PendingView
          available={available}
          preview={preview}
          claim={preview ? previewClaim({ approval_sent_to: demoCompany.corporate_email, mc_number: demoCompany.mc_number }) : claim}
          company={preview ? demoCompany : company}
          membership={preview ? previewMembership({ status: 'pending' }) : membership}
        />
      )}

      {view === 'approvals' && (
        <ApprovalsView me={me} preview={preview} approvals={preview ? PREVIEW_APPROVALS : approvals} />
      )}

      {(view === 'agent' || view === 'admin') && (
        <CompanyConsole
          company={preview ? demoCompany : company!}
          myRole={preview ? (view === 'admin' ? 'company_owner' : 'broker_agent') : membership!.role}
          members={preview ? PREVIEW_MEMBERS : members}
          audit={preview ? PREVIEW_AUDIT : audit}
          brokerPage={preview ? null : brokerPage}
        />
      )}
    </CompanyPreviewContext.Provider>
  )
}

/* ---------------- Not connected: the three steps + the button ---------------- */

function NotConnected({
  me,
  isCarrier,
  available,
  preview,
  claim,
  company,
  membership,
}: {
  me: { email: string; name: string }
  isCarrier: boolean
  available: boolean
  preview: boolean
  claim: CompanyClaim | null
  company: Company | null
  membership: CompanyMembership | null
}) {
  const kind = isCarrier ? 'carrier' : 'broker'
  return (
    <div className="mt-6 space-y-5">
      <Card>
        <CardHeader>
          <CardTitle className="text-base">You are not connected to a company yet</CardTitle>
          <CardDescription>
            Signed in as <span className="font-semibold">{me.email}</span>. This email is not linked to a{' '}
            {kind} company in HeavyHaul Agent. Connecting is optional — you can keep using the
            platform without it. Once approved, you get the corporate profile, your company&apos;s
            team list and the &quot;Approved company {isCarrier ? 'agent' : 'broker agent'}&quot; badge.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <ol className="grid gap-3 sm:grid-cols-3">
            {[
              ['1', 'Verify your company access', 'Type your company’s MC number. We find the company and its corporate email on file.'],
              ['2', 'The company approves you', 'A request goes to the corporate email. Whoever owns that mailbox approves or denies it — by the link in the email, or right here if they sign in with that email.'],
              ['3', 'You are connected', 'Your status becomes “Approved company agent”. The first person approved for a company becomes its Company Owner and can manage the corporate profile and the team.'],
            ].map(([n, title, body]) => (
              <li key={n} className="rounded-xl border bg-white p-4 text-sm">
                <span className="grid h-6 w-6 place-items-center rounded-full bg-[#0f1b2d] text-[11px] font-bold text-[#f5a623]">{n}</span>
                <p className="mt-2 font-semibold">{title}</p>
                <p className="mt-1 text-xs leading-relaxed text-neutral-500">{body}</p>
              </li>
            ))}
          </ol>
          <div className="mt-5">
            {/* The one button — the same pop-up as Settings (Task 89). */}
            <CompanyAccessCard
              available={available}
              company={company}
              membership={membership}
              claim={claim}
              preview={preview}
              embedded
            />
          </div>
        </CardContent>
      </Card>
      <p className="text-xs text-neutral-500">
        Already the company&apos;s corporate contact? Requests to represent your company appear on this
        page as &quot;Approvals for you&quot; when you sign in with the corporate email on file.
      </p>
    </div>
  )
}

/* ---------------- Request pending ---------------- */

function PendingView({
  available,
  preview,
  claim,
  company,
  membership,
}: {
  available: boolean
  preview: boolean
  claim: CompanyClaim | null
  company: Company | null
  membership: CompanyMembership | null
}) {
  return (
    <div className="mt-6 space-y-4">
      <Card>
        <CardHeader>
          <CardTitle className="text-base">Your request is with the company</CardTitle>
          <CardDescription>
            Nothing else is needed from you. You will see the result here and in Settings; the
            corporate contact can approve from the email link or from this page.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <CompanyAccessCard
            available={available}
            company={company}
            membership={membership}
            claim={claim}
            preview={preview}
            embedded
          />
        </CardContent>
      </Card>
    </div>
  )
}

/* ---------------- Approvals for the corporate contact ---------------- */

function ApprovalsView({
  me,
  preview,
  approvals,
}: {
  me: { email: string }
  preview: boolean
  approvals: AwaitingApprovalView[]
}) {
  const router = useRouter()
  const [busy, setBusy] = useState<string | null>(null)
  const [done, setDone] = useState<Record<string, string>>({})

  async function decide(a: AwaitingApprovalView, decision: 'approve' | 'deny' | 'report') {
    const outcome =
      decision === 'approve' ? 'Approved' : decision === 'deny' ? 'Denied' : 'Reported to HeavyHaul Agent'
    if (preview) {
      setDone((d) => ({ ...d, [a.claim.id]: outcome }))
      toast.info(`${outcome} — design preview, nothing is saved.`)
      return
    }
    setBusy(a.claim.id)
    try {
      const res = await fetch('/api/company/claims', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ op: 'corporate_decide', claim_id: a.claim.id, decision }),
      })
      const json = await res.json().catch(() => ({}))
      if (!res.ok) {
        toast.error(json.error ?? 'Could not record your decision')
        return
      }
      setDone((d) => ({ ...d, [a.claim.id]: outcome }))
      toast.success(
        decision === 'approve'
          ? `${a.requester.name} is now an approved agent of ${a.company.display_name}`
          : decision === 'deny'
            ? 'Request denied'
            : 'Reported — HeavyHaul Agent will review this request',
      )
      router.refresh()
    } finally {
      setBusy(null)
    }
  }

  return (
    <div className="mt-6 space-y-4">
      <Card>
        <CardHeader>
          <CardTitle className="text-base">Requests waiting for your approval</CardTitle>
          <CardDescription>
            You are signed in as <span className="font-semibold">{me.email}</span>, the corporate contact
            on file for the company below. Approve only if this person is authorized to create
            trips, manage permit intake, and interact with carriers on behalf of your company.
            Your name, email and the time are recorded with the decision.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          {approvals.length === 0 && (
            <p className="rounded-xl border border-dashed p-4 text-center text-sm text-neutral-500">
              No requests are waiting for you.
            </p>
          )}
          {approvals.map((a) => (
            <div key={a.claim.id} className="rounded-xl border bg-white p-4">
              <div className="flex flex-wrap items-start justify-between gap-3">
                <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-sm">
                  <dt className="text-neutral-500">Name</dt>
                  <dd className="font-semibold">{a.requester.name}</dd>
                  <dt className="text-neutral-500">Email</dt>
                  <dd className="font-semibold">{a.requester.email}</dd>
                  <dt className="text-neutral-500">Phone</dt>
                  <dd>{a.requester.phone ?? '—'}</dd>
                  <dt className="text-neutral-500">Company</dt>
                  <dd>
                    {a.company.display_name}
                    {a.claim.mc_number ? ` · MC ${a.claim.mc_number}` : ''}
                  </dd>
                  <dt className="text-neutral-500">Requested role</dt>
                  <dd>{companyRoleLabel(a.claim.requested_role, a.company.company_type)}</dd>
                  <dt className="text-neutral-500">Access level</dt>
                  <dd>Create trips, send intake links, request permits</dd>
                  <dt className="text-neutral-500">Requested</dt>
                  <dd>{formatFullDate(a.claim.created_at)}</dd>
                </dl>
                {done[a.claim.id] ? (
                  <span className="rounded-full bg-neutral-100 px-3 py-1 text-xs font-semibold text-neutral-700">
                    {done[a.claim.id]}
                  </span>
                ) : (
                  <div className="flex flex-wrap gap-2">
                    <Button
                      size="sm"
                      disabled={busy === a.claim.id}
                      onClick={() => decide(a, 'approve')}
                      className="bg-green-700 hover:bg-green-800"
                    >
                      Approve
                    </Button>
                    <Button size="sm" variant="outline" disabled={busy === a.claim.id} onClick={() => decide(a, 'deny')}>
                      Deny
                    </Button>
                    <Button
                      size="sm"
                      variant="ghost"
                      disabled={busy === a.claim.id}
                      onClick={() => decide(a, 'report')}
                      className="text-red-700"
                      title="I do not know this person — send it to HeavyHaul Agent for review"
                    >
                      Report unknown person
                    </Button>
                  </div>
                )}
              </div>
            </div>
          ))}
        </CardContent>
      </Card>
    </div>
  )
}
