'use client'

import { useEffect, useMemo, useState } from "react"
import {
  AlertTriangle,
  ArrowDownRight,
  ArrowUpRight,
  Ban,
  CheckCircle2,
  Clock,
  FileCheck,
  Send,
  ShieldCheck,
  ShoppingCart,
  XCircle,
} from "lucide-react"
import { toast } from "sonner"
import { useOrders } from "@/hooks/useOrders"
import type { CombinedOrderRead, OrderWorkflowAction } from "@/types"
import { PageHeader } from "@/components/ui/page-header"
import { KpiCard } from "@/components/ui/kpi-card"
import { SectionCard } from "@/components/ui/section-card"
import { DataTable, type Column } from "@/components/ui/data-table"
import { StatusBadge, type StatusTone } from "@/components/ui/status-badge"
import { Button } from "@/components/ui/button"
import { Modal } from "@/components/ui/modal"
import { TextAreaField } from "@/components/ui/FormFields"
import { fmtMoney, fmtGrams, formatDateTime } from "@/lib/format"
import { useTranslation } from "react-i18next"

const statusMap: Record<string, { key: string; tone: StatusTone }> = {
  draft: { key: "draft", tone: "neutral" },
  pending_review: { key: "pending_review", tone: "pending" },
  pending_approval: { key: "pending_approval", tone: "warning" },
  approved: { key: "approved", tone: "success" },
  posted: { key: "posted", tone: "success" },
  rejected: { key: "rejected", tone: "danger" },
  cancelled: { key: "cancelled", tone: "neutral" },
  sent_to_supplier: { key: "sent", tone: "info" },
  partially_supplied: { key: "partial", tone: "warning" },
  fully_supplied: { key: "supplied", tone: "success" },
  delivering: { key: "delivering", tone: "info" },
  delivered: { key: "delivered", tone: "success" },
  closed: { key: "closed", tone: "neutral" },
}

const actionLabels: Record<OrderWorkflowAction, string> = {
  "submit-for-review": "submit_review",
  "submit-for-approval": "submit_approval",
  approve: "approve",
  reject: "reject",
  cancel: "cancel",
  post: "post",
}

const actionIcons: Record<OrderWorkflowAction, typeof Send> = {
  "submit-for-review": Send,
  "submit-for-approval": ShieldCheck,
  approve: CheckCircle2,
  reject: XCircle,
  cancel: Ban,
  post: FileCheck,
}

function availableActions(order: CombinedOrderRead): OrderWorkflowAction[] {
  switch (order.status) {
    case "draft":
      return ["submit-for-review", "cancel"]
    case "pending_review":
      return ["submit-for-approval", "reject", "cancel"]
    case "pending_approval":
      return ["approve", "reject", "cancel"]
    case "approved":
      return ["post", "cancel"]
    default:
      return []
  }
}

function requiresReason(action: OrderWorkflowAction | null) {
  return action === "reject" || action === "cancel"
}

function statusTone(status: string) {
  return statusMap[status]?.tone ?? "neutral"
}

export default function OrdersPage() {
  const { t } = useTranslation()
  const tr = (key: string, options?: Record<string, unknown>) => t(`app.admin.orders.page.${key}`, options)
  const {
    items: rows,
    totalCount,
    fetchItems,
    isLoading,
    isSubmitting,
    error,
    postingResult,
    transitionOrder,
    orderDetails,
    fetchOrderDetails,
  } = useOrders()

  const [selectedKey, setSelectedKey] = useState<string | null>(null)
  const [actionOpen, setActionOpen] = useState(false)
  const [selectedAction, setSelectedAction] = useState<OrderWorkflowAction | null>(null)
  const [actionNote, setActionNote] = useState("")

  useEffect(() => {
    fetchItems()
  }, [fetchItems])

  const selected = useMemo(() => {
    if (!rows.length) return null
    if (!selectedKey) return rows[0]
    return rows.find((row) => `${row.order_type}-${row.id}` === selectedKey) ?? rows[0]
  }, [rows, selectedKey])

  useEffect(() => {
    if (selected) {
      fetchOrderDetails(selected.id, selected.order_type)
    }
  }, [selected?.id, selected?.order_type, fetchOrderDetails])

  const totals = useMemo(() => {
    return rows.reduce(
      (acc, row) => {
        const amount = Number(row.total_amount) || 0
        if (row.order_type === "buy") acc.buyVolume += amount
        if (row.order_type === "sell") acc.sellVolume += amount
        if (["failed", "incident", "rejected", "cancelled"].includes(row.status)) acc.exceptionCount += 1
        acc.feeRevenue += Number(row.fee_amount) || 0
        return acc
      },
      { buyVolume: 0, sellVolume: 0, exceptionCount: 0, feeRevenue: 0 },
    )
  }, [rows])

  const columns: Column<CombinedOrderRead>[] = [
    {
      key: "code",
      header: tr("order"),
      cell: (row) => <span className="font-mono text-[12.5px] font-semibold">{row.order_no}</span>,
    },
    {
      key: "customer",
      header: tr("customer"),
      cell: (row) => (
        <span className="text-[13px]">
          {row.customer_name || row.customer_id?.slice(0, 8) || row.user_id?.slice(0, 8) || "-"}
        </span>
      ),
    },
    {
      key: "side",
      header: tr("side"),
      cell: (row) => (
        <span className={`inline-flex items-center gap-1 rounded-md px-2 py-0.5 text-[11.5px] font-semibold ${row.order_type === "buy" ? "bg-emerald-50 text-emerald-700" : "bg-red-50 text-red-700"}`}>
          {row.order_type === "buy" ? <ArrowDownRight className="h-3 w-3" /> : <ArrowUpRight className="h-3 w-3" />}
          {row.order_type === "buy" ? tr("buy") : tr("sell")}
        </span>
      ),
    },
    {
      key: "qty",
      header: tr("grams"),
      cell: (row) => <span className="font-mono tabular-nums text-[13px]">{fmtGrams(Number(row.requested_grams) || 0)}</span>,
    },
    {
      key: "total",
      header: tr("total"),
      cell: (row) => <span className="font-mono tabular-nums text-[13px] font-semibold">{fmtMoney(Number(row.total_amount) || 0)}</span>,
    },
    {
      key: "status",
      header: tr("status"),
      cell: (row) => (
        <StatusBadge tone={statusTone(row.status)} size="sm">
          {statusMap[row.status] ? tr(statusMap[row.status].key) : row.status}
        </StatusBadge>
      ),
    },
  ]

  const openAction = (action: OrderWorkflowAction) => {
    setSelectedAction(action)
    setActionNote("")
    setActionOpen(true)
  }

  const submitAction = async () => {
    if (!selected || !selectedAction) return
    if (requiresReason(selectedAction) && !actionNote.trim()) {
      toast.error(tr("reason_required"))
      return
    }

    const ok = await transitionOrder(selected, selectedAction, actionNote.trim() || undefined)
    if (ok) {
      toast.success(tr("action_completed", { action: tr(actionLabels[selectedAction]) }))
      setActionOpen(false)
      setSelectedAction(null)
      setActionNote("")
    }
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title={tr("title")}
        description={tr("description")}
        breadcrumbs={[{ label: tr("financial_operations"), href: "#" }, { label: tr("orders") }]}
        actions={
          <Button variant="outline" className="min-w-28" onClick={() => fetchItems()} disabled={isLoading}>
            <Clock className="h-4 w-4" />
            {tr("refresh")}
          </Button>
        }
      />

      <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
        <KpiCard label={tr("total_orders")} value={String(totalCount)} icon={ShoppingCart} tone="gold" accent />
        <KpiCard label={tr("buy_volume")} value={fmtMoney(totals.buyVolume)} icon={ArrowDownRight} tone="success" />
        <KpiCard label={tr("sell_volume")} value={fmtMoney(totals.sellVolume)} icon={ArrowUpRight} tone="info" />
        <KpiCard label={tr("exceptions")} value={String(totals.exceptionCount)} icon={AlertTriangle} tone="danger" />
      </div>

      <div className="grid gap-6 lg:grid-cols-[1fr_400px]">
        <SectionCard title={tr("recent_orders")} padded={false}>
          {error ? (
            <div className="mx-5 mt-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div>
          ) : null}
          {isLoading ? (
            <div className="flex h-48 items-center justify-center">
              <div className="h-8 w-8 animate-spin rounded-full border-4 border-gold-500 border-t-transparent" />
            </div>
          ) : rows.length === 0 ? (
            <div className="px-5 py-8 text-center text-[12.5px] text-muted-foreground">{tr("no_orders")}</div>
          ) : (
            <DataTable
              columns={columns}
              data={rows}
              rowKey={(row) => `${row.order_type}-${row.id}`}
              activeRowKey={selected ? `${selected.order_type}-${selected.id}` : undefined}
              onRowClick={(row) => setSelectedKey(`${row.order_type}-${row.id}`)}
              ariaLabel={tr("title")}
            />
          )}
        </SectionCard>

        <SectionCard title={selected ? tr("order_number", { orderNo: selected.order_no }) : tr("details")}>
          {selected ? (
            <div className="space-y-4">
              <div className="rounded-lg border border-border bg-muted/30 p-4 space-y-2">
                <Row label={tr("side")} value={selected.order_type === "buy" ? tr("buy") : tr("sell")} />
                <Row label={tr("workflow")} value={selected.workflow_type} />
                <Row label={tr("priority")} value={selected.priority} />
                <Row label={tr("grams")} value={fmtGrams(Number(selected.requested_grams) || 0)} />
                <Row label={tr("total")} value={fmtMoney(Number(selected.total_amount) || 0)} />
              </div>

              <div className="rounded-lg border border-border bg-muted/30 p-3 space-y-2">
                <Row label={tr("status")} value={statusMap[selected.status] ? tr(statusMap[selected.status].key) : selected.status} />
                <Row label={tr("created")} value={formatDateTime(selected.created_at)} />
                <Row label={tr("reviewed")} value={selected.reviewed_at ? formatDateTime(selected.reviewed_at) : "-"} />
                <Row label={tr("approved")} value={selected.approved_at ? formatDateTime(selected.approved_at) : "-"} />
                <Row label={tr("posted")} value={selected.posted_at ? formatDateTime(selected.posted_at) : "-"} />
              </div>

              <div className="grid grid-cols-3 gap-2 pt-1 text-center">
                <StepTile label={tr("created")} active />
                <StepTile label={tr("approved")} active={Boolean(selected.approved_at || ["approved", "posted", "closed"].includes(selected.status))} />
                <StepTile label={tr("posted")} active={Boolean(selected.posted_at || selected.status === "posted")} />
              </div>

              <div className="grid gap-2 border-t border-border pt-4">
                {availableActions(selected).length === 0 ? (
                  <div className="rounded-md border border-border bg-muted/30 px-3 py-2 text-[12.5px] text-muted-foreground">
                    {tr("read_only")}
                  </div>
                ) : (
                  availableActions(selected).map((action) => {
                    const Icon = actionIcons[action]
                    return (
                      <Button
                        key={action}
                        variant={action === "reject" || action === "cancel" ? "outline" : "primary"}
                        className="min-h-10"
                        onClick={() => openAction(action)}
                        disabled={isSubmitting}
                      >
                        <Icon className="h-4 w-4" />
                        {tr(actionLabels[action])}
                      </Button>
                    )
                  })
                )}
              </div>

              {postingResult ? (
                <div className="rounded-lg border border-emerald-200 bg-emerald-50 p-3 text-[12.5px] text-emerald-800">
                  {tr("posting_result", { orderNo: postingResult.order_no, journalCount: postingResult.journal_entries.length, cashCount: postingResult.cash_postings.length, goldCount: postingResult.gold_postings.length })}
                </div>
              ) : null}
            </div>
          ) : (
            <p className="text-[13px] text-muted-foreground">{tr("select_order")}</p>
          )}
        </SectionCard>
      </div>

      <SectionCard title={tr("financial_summary")}>
        <div className="grid grid-cols-3 gap-4">
          <SummaryMetric label={tr("fee_revenue")} value={fmtMoney(totals.feeRevenue)} />
          <SummaryMetric label={tr("net_buy")} value={fmtMoney(totals.buyVolume)} tone="success" />
          <SummaryMetric label={tr("net_sell")} value={fmtMoney(totals.sellVolume)} tone="danger" />
        </div>
      </SectionCard>

      {selected ? (
        <div className="grid gap-6 lg:grid-cols-2">
          <SectionCard title={tr("postings")}>
            {orderDetails.isLoading ? (
              <div className="flex h-32 items-center justify-center">
                <div className="h-6 w-6 animate-spin rounded-full border-4 border-gold-500 border-t-transparent" />
              </div>
            ) : orderDetails.postings ? (
              <div className="space-y-4">
                <div className="rounded-lg border border-border bg-muted/30 p-3 text-[12.5px]">
                  <p className="font-semibold mb-2">{tr("journal_entries")}</p>
                  {orderDetails.postings.journal_entries.length > 0 ? (
                    <ul className="space-y-1">
                      {orderDetails.postings.journal_entries.map((j: any, i: number) => (
                        <li key={i} className="flex justify-between items-center gap-2">
                          <span className="font-mono bg-muted px-1 rounded">{j.journal_number}</span>
                          <span className="text-muted-foreground text-right">{j.type}</span>
                        </li>
                      ))}
                    </ul>
                  ) : <p className="text-muted-foreground">{tr("no_journal_entries")}</p>}
                </div>
                <div className="rounded-lg border border-border bg-muted/30 p-3 text-[12.5px]">
                  <p className="font-semibold mb-2">{tr("cash_postings")}</p>
                  {orderDetails.postings.cash_postings.length > 0 ? (
                    <ul className="space-y-1">
                      {orderDetails.postings.cash_postings.map((c: any, i: number) => (
                        <li key={i} className="flex justify-between">
                          <span className="font-mono">{fmtMoney(Number(c.amount))}</span>
                          <span className="uppercase text-muted-foreground">{c.entry_type}</span>
                        </li>
                      ))}
                    </ul>
                  ) : <p className="text-muted-foreground">{tr("no_cash_postings")}</p>}
                </div>
                <div className="rounded-lg border border-border bg-muted/30 p-3 text-[12.5px]">
                  <p className="font-semibold mb-2">{tr("gold_postings")}</p>
                  {orderDetails.postings.gold_postings.length > 0 ? (
                    <ul className="space-y-1">
                      {orderDetails.postings.gold_postings.map((g: any, i: number) => (
                        <li key={i} className="flex justify-between">
                          <span className="font-mono">{fmtGrams(Number(g.grams))}</span>
                          <span className="uppercase text-muted-foreground">{g.entry_type}</span>
                        </li>
                      ))}
                    </ul>
                  ) : <p className="text-muted-foreground">{tr("no_gold_postings")}</p>}
                </div>
              </div>
            ) : (
              <p className="text-[13px] text-muted-foreground px-5 py-8 text-center">{tr("no_postings")}</p>
            )}
          </SectionCard>

          <SectionCard title={tr("audit_logs")}>
            {orderDetails.isLoading ? (
              <div className="flex h-32 items-center justify-center">
                <div className="h-6 w-6 animate-spin rounded-full border-4 border-gold-500 border-t-transparent" />
              </div>
            ) : orderDetails.auditLogs.length > 0 ? (
              <div className="space-y-2 h-[400px] overflow-auto pr-2">
                {orderDetails.auditLogs.map((log: any, i: number) => (
                  <div key={i} className="rounded-lg border border-border bg-muted/30 p-3 text-[12.5px]">
                    <div className="flex justify-between font-semibold">
                      <span>{log.action.replace(/_/g, ' ').toUpperCase()}</span>
                      <span className="text-muted-foreground font-normal">{formatDateTime(log.created_at)}</span>
                    </div>
                    {log.details && Object.keys(log.details).length > 0 && (
                      <pre className="mt-2 rounded bg-muted/50 p-2 text-[10.5px] text-muted-foreground overflow-auto">
                        {JSON.stringify(log.details, null, 2)}
                      </pre>
                    )}
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-[13px] text-muted-foreground px-5 py-8 text-center">{tr("no_audit_logs")}</p>
            )}
          </SectionCard>
        </div>
      ) : null}

      <Modal
        open={actionOpen}
        onClose={() => {
          setActionOpen(false)
          setSelectedAction(null)
          setActionNote("")
        }}
        title={selectedAction ? tr(actionLabels[selectedAction]) : tr("order_action")}
        description={selected ? `${selected.order_no} (${selected.order_type})` : undefined}
        size="sm"
      >
        <div className="space-y-4">
          <TextAreaField
            label={requiresReason(selectedAction) ? tr("reason") : tr("note")}
            id="order-action-note"
            name="note"
            value={actionNote}
            rows={4}
            onChange={(event) => setActionNote(event.target.value)}
            placeholder={requiresReason(selectedAction) ? tr("required_reason") : tr("optional_note")}
            required={requiresReason(selectedAction)}
          />
          <div className="flex justify-end gap-2 border-t border-border pt-4">
            <Button variant="outline" onClick={() => setActionOpen(false)}>{tr("close")}</Button>
            <Button
              variant={selectedAction === "reject" || selectedAction === "cancel" ? "danger" : "primary"}
              onClick={submitAction}
              isLoading={isSubmitting}
            >
              {selectedAction ? tr(actionLabels[selectedAction]) : tr("confirm")}
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  )
}

function Row({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-center justify-between gap-3 text-[12.5px]">
      <span className="text-muted-foreground">{label}</span>
      <span className="text-right font-mono tabular-nums">{value}</span>
    </div>
  )
}

function StepTile({ label, active }: { label: string; active: boolean }) {
  return (
    <div className={`rounded-md border p-2 ${active ? "border-emerald-200 bg-emerald-50" : "border-border"}`}>
      <CheckCircle2 className={`mx-auto h-3.5 w-3.5 ${active ? "text-emerald-600" : "text-muted-foreground"}`} />
      <p className="mt-1 text-[10.5px] text-muted-foreground">{label}</p>
    </div>
  )
}

function SummaryMetric({ label, value, tone }: { label: string; value: string; tone?: "success" | "danger" }) {
  return (
    <div>
      <p className="text-[11.5px] uppercase tracking-wider text-muted-foreground">{label}</p>
      <p className={`mt-1 font-mono text-[20px] font-bold tabular-nums ${tone === "success" ? "text-emerald-600" : tone === "danger" ? "text-red-600" : ""}`}>
        {value}
      </p>
    </div>
  )
}
