"use client"

import { use, useEffect, useRef, useState } from "react"
import Link from "next/link"
import { ArrowLeft, FileBarChart } from "lucide-react"

import { salesApi } from "@/lib/api/sales"
import { errorMessage } from "@/lib/error-map"
import { Button, buttonVariants } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Skeleton } from "@/components/ui/skeleton"
import { SalesReportDefinition } from "@/types/sales"

function formatHeader(key: string) {
  return key
    .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
    .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
    .replace(/_/g, " ")
    .trim()
}

function formatCell(value: unknown): string {
  if (value === null || value === undefined) return ""
  if (typeof value === "number") return value.toLocaleString("en-LK", { maximumFractionDigits: 2 })
  if (typeof value === "string") {
    const isoDate = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(value) || /^\d{4}-\d{2}-\d{2}$/.test(value)
    if (isoDate) {
      const parsed = new Date(value)
      if (!Number.isNaN(parsed.getTime())) {
        return new Intl.DateTimeFormat("en-LK", {
          year: "numeric",
          month: "short",
          day: "2-digit",
        }).format(parsed)
      }
    }
    return value
  }
  if (typeof value === "boolean") return value ? "Yes" : "No"
  if (Array.isArray(value)) return value.map((item) => formatCell(item)).join(", ")
  if (typeof value === "object") return JSON.stringify(value)
  return String(value)
}

const reportColumns: Record<string, string[]> = {
  "daily-summary": ["date", "invoiceCount", "slipCount", "invoiceSubtotal", "slipSubtotal", "discountTotal", "freeQtyTotal", "taxTotal", "grandTotal"],
  "item-summary": ["itemId", "itemName", "soldQty", "freeQty", "grossAmount", "discountTotal", "taxTotal", "netAmount"],
  "customer-summary": ["customerId", "customerName", "invoiceCount", "slipCount", "soldQty", "freeQty", "grossAmount", "discountTotal", "taxTotal", "netAmount"],
  "warehouse-summary": ["warehouseId", "warehouseName", "invoiceCount", "slipCount", "soldQty", "freeQty", "grossAmount", "discountTotal", "taxTotal", "netAmount"],
  "discount-summary": ["documentType", "documentNo", "documentDate", "customerName", "subtotal", "discountTotal", "taxTotal", "netAmount"],
  "free-issue-summary": ["documentType", "documentNo", "documentDate", "customerName", "itemId", "itemName", "freeQty", "freeValue", "warehouseId", "warehouseName"],
}

export default function SalesReportDetailPage({ params }: { params: Promise<{ reportId: string }> }) {
  const resolvedParams = use(params)
  const [report, setReport] = useState<SalesReportDefinition | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)
  const [from, setFrom] = useState("")
  const [to, setTo] = useState("")
  const [queryLoading, setQueryLoading] = useState(false)
  const [rows, setRows] = useState<unknown[] | null>(null)
  const [queryError, setQueryError] = useState<string | null>(null)
  const lastAutoRunKey = useRef<string>("")

  useEffect(() => {
    setError(null)
    setLoading(true)
    salesApi.getReport(resolvedParams.reportId)
      .then(setReport)
      .catch((err) => setError(errorMessage(err)))
      .finally(() => setLoading(false))
  }, [resolvedParams.reportId])

  useEffect(() => {
    const now = new Date()
    const firstDay = new Date(now.getFullYear(), now.getMonth(), 1)
    setFrom(firstDay.toISOString().slice(0, 10))
    setTo(now.toISOString().slice(0, 10))
  }, [resolvedParams.reportId])

  useEffect(() => {
    if (!report || !from || !to) return

    const runKey = `${report.id}:${from}:${to}`
    if (lastAutoRunKey.current === runKey) return

    lastAutoRunKey.current = runKey
    setQueryError(null)
    setQueryLoading(true)
    salesApi
      .queryReport({
        reportType: report.id,
        from,
        to,
      })
      .then((response) => setRows(response.rows))
      .catch((err) => {
        setRows(null)
        setQueryError(errorMessage(err))
      })
      .finally(() => setQueryLoading(false))
  }, [report, from, to])

  const runReport = () => {
    if (!report) return
    if (!from || !to) {
      setQueryError("Select both from and to dates.")
      setRows(null)
      return
    }

    lastAutoRunKey.current = `${report.id}:${from}:${to}`
    setQueryError(null)
    setQueryLoading(true)
    salesApi
      .queryReport({
        reportType: report.id,
        from,
        to,
      })
      .then((response) => setRows(response.rows))
      .catch((err) => {
        setRows(null)
        setQueryError(errorMessage(err))
      })
      .finally(() => setQueryLoading(false))
  }

  const columns = report ? (reportColumns[report.id] ?? (rows && rows.length > 0 ? Object.keys(rows[0] as Record<string, unknown>) : [])) : []

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center gap-3">
        <Link href="/dashboard/sales/reports" className={buttonVariants({ variant: "outline", size: "icon" })}>
          <ArrowLeft className="size-4" />
        </Link>
        <div>
          <h1 className="text-2xl font-bold text-foreground">Report Details</h1>
          <p className="text-base text-muted-foreground">Metadata for the selected sales report.</p>
        </div>
      </div>

      {error && <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-5 text-base text-destructive">{error}</div>}

      {!error && loading && <Skeleton className="h-48 rounded-2xl" />}

      {!error && !loading && report === null && (
        <div className="rounded-2xl border border-dashed p-8 text-base text-muted-foreground">
          Report metadata could not be loaded. The report id may be invalid, or your session may have expired.
        </div>
      )}

      {!error && report && (
        <div className="space-y-4">
          <Card>
            <CardHeader>
              <div className="flex items-center gap-3">
                <div className="flex size-11 items-center justify-center rounded-xl bg-primary/10 text-primary">
                  <FileBarChart className="size-5" />
                </div>
                <div>
                  <CardTitle className="text-lg">{report.name}</CardTitle>
                  <p className="mt-1 text-sm text-muted-foreground">{report.id}</p>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <p className="text-base text-muted-foreground">{report.description}</p>
            </CardContent>
          </Card>

          {resolvedParams.reportId !== "daily-summary" && (
          <Card>
            <CardContent className="grid gap-4 p-4 sm:grid-cols-2 lg:grid-cols-3">
              <div className="space-y-2">
                <label className="text-sm font-medium text-foreground">From</label>
                <Input type="date" value={from} onChange={(e) => setFrom(e.target.value)} />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium text-foreground">To</label>
                  <Input type="date" value={to} onChange={(e) => setTo(e.target.value)} />
              </div>
              <div className="flex items-end">
                <Button type="button" className="w-full sm:w-auto" onClick={runReport} disabled={queryLoading}>
                  Run report
                </Button>
                </div>
              </CardContent>
            </Card>
          )}

          {queryError && <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-5 text-base text-destructive">{queryError}</div>}

          {queryLoading && <Skeleton className="h-40 rounded-2xl" />}

          {!queryLoading && rows && rows.length === 0 && (
            <div className="rounded-lg border border-dashed p-8 text-sm text-muted-foreground">
              No rows returned for the selected date range.
            </div>
          )}

          {!queryLoading && rows && rows.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Report Results</CardTitle>
              </CardHeader>
              <CardContent className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead className="bg-secondary/60 text-[11px] uppercase tracking-wide text-muted-foreground">
                    <tr>
                      {columns.map((key) => (
                        <th key={key} className="px-4 py-2 text-left font-medium">
                          {formatHeader(key)}
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {rows.map((row, index) => {
                      const record = row as Record<string, unknown>
                      return (
                        <tr key={index} className="border-t border-border hover:bg-secondary/40">
                          {columns.map((key) => (
                            <td key={key} className="px-4 py-2.5 align-top">
                              {formatCell(record[key])}
                            </td>
                          ))}
                        </tr>
                      )
                    })}
                  </tbody>
                </table>
              </CardContent>
            </Card>
          )}
        </div>
      )}
    </div>
  )
}
