import * as React from "react"
import { Section, Text } from "@react-email/components"

import { EMAIL_COLORS } from "./tokens"
import { formatPriority, formatStatus } from "./utils"

export type TicketCardData = {
  reference: number
  subject: string
  companyName?: string | null
  status?: string | null
  priority?: string | null
  requesterName?: string | null
  assigneeName?: string | null
}

export type TicketCardProps = {
  ticketNumber: string
  ticketTitle: string
  status?: string | null
  priority?: string | null
  category?: string | null
  subcategory?: string | null
  companyName?: string | null
  requesterName?: string | null
  assigneeName?: string | null
}

function badge(label: string, bg: string, color: string) {
  return (
    <span
      style={{
        display: "inline-block",
        padding: "4px 12px",
        borderRadius: "999px",
        fontSize: "12px",
        fontWeight: 700,
        backgroundColor: bg,
        color,
        whiteSpace: "nowrap",
      }}
    >
      {label}
    </span>
  )
}

function statusBadge(status: string) {
  const normalized = status.trim().toUpperCase()
  const map: Record<string, { bg: string; color: string; label: string }> = {
    PENDING: { bg: EMAIL_COLORS.statusPendingBg, color: EMAIL_COLORS.statusPending, label: "Pendente" },
    AWAITING_ATTENDANCE: { bg: EMAIL_COLORS.statusProgressBg, color: EMAIL_COLORS.statusProgress, label: "Em andamento" },
    PAUSED: { bg: EMAIL_COLORS.statusPausedBg, color: EMAIL_COLORS.statusPaused, label: "Pausado" },
    RESOLVED: { bg: EMAIL_COLORS.statusResolvedBg, color: EMAIL_COLORS.statusResolved, label: "Resolvido" },
  }
  const entry = map[normalized] ?? {
    bg: EMAIL_COLORS.statusPendingBg,
    color: EMAIL_COLORS.statusPending,
    label: formatStatus(status),
  }
  return badge(entry.label, entry.bg, entry.color)
}

function priorityBadge(priority: string) {
  const normalized = priority.trim().toUpperCase()
  const map: Record<string, { bg: string; color: string; label: string }> = {
    LOW: { bg: EMAIL_COLORS.priorityLowBg, color: EMAIL_COLORS.priorityLow, label: "Baixa" },
    MEDIUM: { bg: EMAIL_COLORS.priorityMediumBg, color: EMAIL_COLORS.priorityMedium, label: "Média" },
    HIGH: { bg: EMAIL_COLORS.priorityHighBg, color: EMAIL_COLORS.priorityHigh, label: "Alta" },
    URGENT: { bg: EMAIL_COLORS.priorityUrgentBg, color: EMAIL_COLORS.priorityUrgent, label: "Urgente" },
  }
  const entry = map[normalized] ?? {
    bg: EMAIL_COLORS.priorityMediumBg,
    color: EMAIL_COLORS.priorityMedium,
    label: formatPriority(priority),
  }
  return badge(entry.label, entry.bg, entry.color)
}

function Row({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <tr>
      <td style={{ padding: "6px 10px 6px 0", color: EMAIL_COLORS.textMuted, fontSize: "12px", verticalAlign: "top" }}>
        {label}
      </td>
      <td style={{ padding: "6px 0", color: EMAIL_COLORS.textPrimary, fontSize: "14px" }}>{value}</td>
    </tr>
  )
}

/** @deprecated Use TicketCard with props instead */
export function TicketCardLegacy({ ticket }: { ticket: TicketCardData }) {
  return (
    <Section
      style={{
        backgroundColor: EMAIL_COLORS.background,
        borderRadius: "12px",
        padding: "16px",
        marginTop: "18px",
      }}
    >
      <table cellPadding="0" cellSpacing="0" role="presentation" style={{ width: "100%" }}>
        <tbody>
          <Row label="Chamado" value={<Text style={{ margin: 0, fontWeight: 800 }}>#{ticket.reference}</Text>} />
          <Row label="Assunto" value={ticket.subject} />
          {ticket.companyName ? <Row label="Empresa" value={ticket.companyName} /> : null}
          {ticket.status ? <Row label="Status" value={statusBadge(ticket.status)} /> : null}
          {ticket.priority ? <Row label="Prioridade" value={priorityBadge(ticket.priority)} /> : null}
          {ticket.requesterName ? <Row label="Solicitante" value={ticket.requesterName} /> : null}
          {ticket.assigneeName ? <Row label="Responsável" value={ticket.assigneeName} /> : null}
        </tbody>
      </table>
    </Section>
  )
}

export function TicketCard(props: TicketCardProps) {
  const { ticketNumber, ticketTitle, status, priority, category, subcategory, companyName, requesterName, assigneeName } = props
  const categoryLabel = category && subcategory ? `${category} / ${subcategory}` : category ?? subcategory ?? null

  return (
    <Section
      style={{
        backgroundColor: "#f8fafc",
        borderRadius: "12px",
        border: `1px solid ${EMAIL_COLORS.border}`,
        margin: "24px 0",
      }}
    >
      <table cellPadding="0" cellSpacing="0" role="presentation" style={{ width: "100%" }}>
        <tbody>
          <tr>
            <td style={{ padding: "16px 20px", borderBottom: "1px solid #f1f5f9" }}>
              <Text style={{ margin: 0, fontSize: "13px", fontWeight: 600, color: EMAIL_COLORS.textMuted }}>
                Chamado #{ticketNumber}
              </Text>
              <Text style={{ margin: "4px 0 0 0", fontSize: "16px", fontWeight: 700, color: EMAIL_COLORS.textPrimary }}>
                {ticketTitle}
              </Text>
            </td>
          </tr>
          <tr>
            <td style={{ padding: "16px 20px" }}>
              <table cellPadding="0" cellSpacing="0" role="presentation" style={{ width: "100%" }}>
                <tbody>
                  {status ? (
                    <tr>
                      <td style={{ paddingBottom: "10px", width: "100px", color: EMAIL_COLORS.textMuted, fontSize: "13px", fontWeight: 500 }}>
                        Status
                      </td>
                      <td style={{ paddingBottom: "10px" }}>{statusBadge(status)}</td>
                    </tr>
                  ) : null}
                  {priority ? (
                    <tr>
                      <td style={{ paddingBottom: "10px", width: "100px", color: EMAIL_COLORS.textMuted, fontSize: "13px", fontWeight: 500 }}>
                        Prioridade
                      </td>
                      <td style={{ paddingBottom: "10px" }}>{priorityBadge(priority)}</td>
                    </tr>
                  ) : null}
                  {categoryLabel ? (
                    <tr>
                      <td style={{ paddingBottom: "10px", width: "100px", color: EMAIL_COLORS.textMuted, fontSize: "13px", fontWeight: 500 }}>
                        Categoria
                      </td>
                      <td style={{ paddingBottom: "10px", color: EMAIL_COLORS.textPrimary, fontSize: "14px" }}>{categoryLabel}</td>
                    </tr>
                  ) : null}
                  {companyName ? (
                    <tr>
                      <td style={{ paddingBottom: "10px", width: "100px", color: EMAIL_COLORS.textMuted, fontSize: "13px", fontWeight: 500 }}>
                        Empresa
                      </td>
                      <td style={{ paddingBottom: "10px", color: EMAIL_COLORS.textPrimary, fontSize: "14px" }}>{companyName}</td>
                    </tr>
                  ) : null}
                  {requesterName ? (
                    <tr>
                      <td style={{ paddingBottom: "10px", width: "100px", color: EMAIL_COLORS.textMuted, fontSize: "13px", fontWeight: 500 }}>
                        Solicitante
                      </td>
                      <td style={{ paddingBottom: "10px", color: EMAIL_COLORS.textPrimary, fontSize: "14px" }}>{requesterName}</td>
                    </tr>
                  ) : null}
                  {assigneeName ? (
                    <tr>
                      <td style={{ width: "100px", color: EMAIL_COLORS.textMuted, fontSize: "13px", fontWeight: 500 }}>
                        Responsavel
                      </td>
                      <td style={{ color: EMAIL_COLORS.textPrimary, fontSize: "14px" }}>{assigneeName}</td>
                    </tr>
                  ) : null}
                </tbody>
              </table>
            </td>
          </tr>
        </tbody>
      </table>
    </Section>
  )
}
