'use client'

import { useState } from 'react'
import Link from 'next/link'
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 { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle,
} from '@/components/ui/dialog'
import { companyRoleLabel } from '@/lib/domain/company'
import { formatFullDate } from '@/lib/format'
import type { Company, CompanyClaim, CompanyMembership } from '@/types/db'

/**
 * "Verify your company access" (Task 89) — the Settings card and the pop-up.
 *
 * Nash (2026-09-08): "I can click 'verify your company access'. It gives him
 * a pop-up which is gonna ask for the MC number. The user types the MC
 * number and clicks 'verify'. An email will be sent to the email associated
 * with that company… he gets an alert saying that a verification request was
 * sent to [that email]… something that explains that we sent an email to
 * that specific email to be validated." Optional — the user can skip it.
 *
 * Design preview (Task 83): when the request cannot be stored yet (migration
 * 0013 not applied, or `preview`), the flow still runs end to end on this
 * screen — pop-up → sent alert → "Company approval pending" — without
 * writing anything. Nash: "show what happens if API would have worked."
 */
export function CompanyAccessCard({
  available,
  company,
  membership,
  claim: initialClaim,
  preview = false,
  embedded = false,
}: {
  available: boolean
  company: Company | null
  membership: CompanyMembership | null
  claim: CompanyClaim | null
  /** Simulate every action (design preview) — nothing is saved. */
  preview?: boolean
  /** Rendered inside the Company page: no card chrome of its own. */
  embedded?: boolean
}) {
  const router = useRouter()
  const [open, setOpen] = useState(false)
  const [mc, setMc] = useState('')
  const [busy, setBusy] = useState(false)
  const [sent, setSent] = useState<{ to: string; mc: string; company: string; token: string } | null>(null)
  // Local claim: what the screen shows when the request could not be stored
  // (preview / migration missing) — the same states, just not persisted.
  const [localClaim, setLocalClaim] = useState<CompanyClaim | null>(null)
  const claim = localClaim ?? initialClaim
  const simulate = preview || !available

  function simulatedClaim(mcDigits: string): CompanyClaim {
    const now = new Date()
    return {
      id: 'preview-claim',
      user_id: 'me',
      company_id: 'preview-company',
      requested_role: 'broker_agent',
      claim_status: 'pending_corporate_approval',
      verification_method: 'corporate_email_approval',
      mc_number: mcDigits,
      approval_sent_to: `verification-demo+mc${mcDigits}@heavyhaulagent.test`,
      approval_token: 'preview-token',
      expires_at: new Date(now.getTime() + 14 * 86_400_000).toISOString(),
      approver_name: null,
      approver_email: null,
      approver_ip: null,
      decided_at: null,
      review_reason: null,
      review_notes: null,
      info_request: null,
      created_at: now.toISOString(),
      updated_at: now.toISOString(),
    }
  }

  async function call(body: Record<string, unknown>) {
    const res = await fetch('/api/company/claims', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    })
    const json = await res.json().catch(() => ({}))
    if (!res.ok) {
      toast.error(json.error ?? 'Something went wrong')
      return null
    }
    return json
  }

  async function verify() {
    if (!mc.trim()) return
    if (simulate) {
      const digits = mc.replace(/\D/g, '')
      if (digits.length < 5 || digits.length > 8) {
        toast.error('Enter the MC number as digits (5–8), e.g. 088374.')
        return
      }
      const c = simulatedClaim(digits)
      setLocalClaim(c)
      setSent({ to: c.approval_sent_to!, mc: digits, company: `Company on file for MC ${digits}`, token: '' })
      return
    }
    setBusy(true)
    try {
      const json = await call({ op: 'request', mc })
      if (!json) return
      setSent({
        to: json.sent_to ?? 'the company admin',
        mc: json.claim?.mc_number ?? mc,
        company: json.company?.display_name ?? 'your company',
        token: json.claim?.approval_token ?? '',
      })
      router.refresh()
    } finally {
      setBusy(false)
    }
  }

  async function resend() {
    if (simulate) {
      toast.success(`Request sent again to ${claim?.approval_sent_to ?? 'the company'} (design preview)`)
      return
    }
    setBusy(true)
    try {
      const json = await call({ op: 'resend' })
      if (json) {
        toast.success(`Request sent again to ${claim?.approval_sent_to ?? 'the company'}`)
        router.refresh()
      }
    } finally {
      setBusy(false)
    }
  }

  async function cancel() {
    if (simulate) {
      setLocalClaim(null)
      setSent(null)
      setMc('')
      setOpen(true)
      return
    }
    setBusy(true)
    try {
      const json = await call({ op: 'cancel' })
      if (json) {
        router.refresh()
        setSent(null)
        setMc('')
        setOpen(true)
      }
    } finally {
      setBusy(false)
    }
  }

  function approvalUrl(token: string) {
    return `${typeof window !== 'undefined' ? window.location.origin : ''}/company-approval/${token}`
  }

  const approved = membership?.status === 'approved' && company
  const pending = !approved && claim && ['pending_corporate_approval', 'company_verification_pending', 'admin_review_required'].includes(claim.claim_status)
  const rejected = !approved && claim?.claim_status === 'rejected'

  const Wrapper = embedded ? EmbeddedShell : CardShell
  return (
    <Wrapper simulate={simulate && !approved}>
        {approved ? (
          <div className="flex flex-wrap items-center justify-between gap-3">
            <div>
              <p className="text-sm font-bold text-green-700">
                ✓ Approved company agent · {companyRoleLabel(membership!.role, company!.company_type)}
              </p>
              <p className="mt-0.5 text-xs text-neutral-500">
                {company!.display_name}
                {company!.mc_number ? ` · MC ${company!.mc_number}` : ''} · Managed by company admin
              </p>
            </div>
            <Link
              href="/company"
              className="rounded-lg bg-[#0f1b2d] px-3 py-2 text-xs font-bold text-white hover:bg-[#1c2f4a]"
            >
              Corporate profile →
            </Link>
          </div>
        ) : pending ? (
          <div className="space-y-3">
            <p className="text-sm font-bold text-amber-700">
              {claim!.claim_status === 'admin_review_required'
                ? 'Under review by HeavyHaul Agent'
                : claim!.claim_status === 'company_verification_pending'
                  ? 'More information requested'
                  : 'Company approval pending'}
            </p>
            <p className="text-xs text-neutral-600">
              Request to represent <span className="font-semibold">{company?.display_name ?? 'your company'}</span>
              {claim!.mc_number ? ` (MC ${claim!.mc_number})` : ''} sent to{' '}
              <span className="font-semibold">{claim!.approval_sent_to ?? 'the company'}</span> on{' '}
              {formatFullDate(claim!.created_at)}.
            </p>
            {claim!.info_request && (
              <p className="rounded-lg border border-amber-200 bg-amber-50 p-3 text-xs text-amber-900">
                <span className="font-semibold">The company asked:</span> {claim!.info_request}
              </p>
            )}
            <div className="flex flex-wrap gap-2">
              {claim!.claim_status === 'pending_corporate_approval' && (
                <Button size="sm" variant="outline" onClick={resend} disabled={busy}>
                  Resend request
                </Button>
              )}
              <Button size="sm" variant="outline" onClick={cancel} disabled={busy}>
                Use a different MC number
              </Button>
              {claim!.claim_status === 'pending_corporate_approval' && (
                <Button
                  size="sm"
                  variant="ghost"
                  onClick={() => {
                    navigator.clipboard.writeText(approvalUrl(claim!.approval_token))
                    toast.success('Approval link copied')
                  }}
                  title="Emails send when the email service connects — until then, share the approval link yourself"
                >
                  Copy approval link
                </Button>
              )}
            </div>
          </div>
        ) : rejected ? (
          <div className="space-y-3">
            <p className="text-sm font-bold text-red-700">Your request to represent this company was not approved.</p>
            <div className="flex flex-wrap gap-2">
              <Button
                size="sm"
                onClick={() => {
                  setSent(null)
                  setMc('')
                  setOpen(true)
                }}
                className="bg-[#0f1b2d] hover:bg-[#1c2f4a]"
              >
                Try again
              </Button>
              <Link href="/support" className="rounded-lg border px-3 py-1.5 text-xs font-semibold hover:bg-neutral-50">
                Contact support
              </Link>
            </div>
          </div>
        ) : (
          <Button
            onClick={() => {
              setSent(null)
              setMc('')
              setOpen(true)
            }}
            className="bg-[#0f1b2d] font-bold hover:bg-[#1c2f4a]"
          >
            Verify your company access
          </Button>
        )}

      {/* The pop-up: one field, one button. */}
      <Dialog open={open} onOpenChange={(o) => !busy && setOpen(o)}>
        <DialogContent className="sm:max-w-md">
          {sent ? (
            <>
              <DialogHeader>
                <DialogTitle className="text-lg">✅ A verification request was sent to {sent.to}.</DialogTitle>
                <DialogDescription className="leading-relaxed">
                  This is the corporate email on file for MC {sent.mc} — {sent.company}. Demo: it is
                  pulled from the FMCSA API once that integration is connected. The company approves
                  or denies your request from that email; you will see the result here.
                </DialogDescription>
              </DialogHeader>
              <div className="mt-2 flex flex-wrap gap-2">
                <Button onClick={() => setOpen(false)} className="bg-[#0f1b2d] font-bold hover:bg-[#1c2f4a]">
                  Done
                </Button>
                {sent.token && (
                  <Button
                    variant="outline"
                    onClick={() => {
                      navigator.clipboard.writeText(approvalUrl(sent.token))
                      toast.success('Approval link copied')
                    }}
                    title="Emails send when the email service connects — until then, share the approval link yourself"
                  >
                    Copy approval link
                  </Button>
                )}
              </div>
            </>
          ) : (
            <form
              onSubmit={(e) => {
                e.preventDefault()
                verify()
              }}
              className="space-y-4"
            >
              <DialogHeader>
                <DialogTitle className="text-lg">Verify your company access</DialogTitle>
                <DialogDescription>
                  We use the MC number to find your company and its corporate email on file.
                </DialogDescription>
              </DialogHeader>
              <div className="space-y-2">
                <Label htmlFor="mc-number">MC number</Label>
                <Input
                  id="mc-number"
                  value={mc}
                  onChange={(e) => setMc(e.target.value)}
                  placeholder="e.g. 088374"
                  inputMode="numeric"
                  autoFocus
                  required
                  className="h-10 text-base"
                />
              </div>
              <div className="flex gap-2">
                <Button type="submit" disabled={busy || !mc.trim()} className="bg-[#0f1b2d] font-bold hover:bg-[#1c2f4a]">
                  {busy ? 'Verifying…' : 'Verify'}
                </Button>
                <Button type="button" variant="ghost" onClick={() => setOpen(false)} disabled={busy}>
                  Cancel
                </Button>
              </div>
            </form>
          )}
        </DialogContent>
      </Dialog>
    </Wrapper>
  )
}

function CardShell({ simulate, children }: { simulate: boolean; children: React.ReactNode }) {
  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-base">Verify your company access</CardTitle>
        <CardDescription>
          Confirm that you are authorized to represent your company. Optional — you can skip this
          and keep using HeavyHaul Agent.
          {simulate && (
            <span className="mt-1 block text-[11px] text-amber-700">
              Design preview — the request is shown but not stored until the company database is connected.
            </span>
          )}
        </CardDescription>
      </CardHeader>
      <CardContent>{children}</CardContent>
    </Card>
  )
}

function EmbeddedShell({ simulate, children }: { simulate: boolean; children: React.ReactNode }) {
  return (
    <div>
      {simulate && (
        <p className="mb-3 text-[11px] text-amber-700">
          Design preview — the request is shown but not stored until the company database is connected.
        </p>
      )}
      {children}
    </div>
  )
}
