"use client"

import { useState, Fragment, Suspense } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { useQueryState, parseAsString } from "nuqs"
import { X } from "lucide-react"
import { Badge, type BadgeProps } from "@/shared/components/ui/badge"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/components/ui/table"
import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"
import { ChevronLeft, ChevronRight } from "lucide-react"
import { formatDate } from "@/shared/lib/utils"
import { cn } from "@/shared/lib/utils"
import type { DataChangeLog, DataChangeStat } from "../types"

interface DataChangeLogTableProps {
  items: DataChangeLog[]
  page: number
  pageSize: number
  total: number
  totalPages: number
  tableOptions: string[]
  stats: DataChangeStat[]
}

function DataChangeLogTableInner({
  items,
  page,
  pageSize,
  total,
  totalPages,
  tableOptions,
  stats,
}: DataChangeLogTableProps) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [expandedId, setExpandedId] = useState<string | null>(null)

  const handlePageChange = (newPage: number) => {
    const params = new URLSearchParams(searchParams.toString())
    if (newPage <= 1) {
      params.delete("page")
    } else {
      params.set("page", String(newPage))
    }
    const query = params.toString()
    router.push(query ? `?${query}` : "?")
  }

  const start = total === 0 ? 0 : (page - 1) * pageSize + 1
  const end = Math.min(page * pageSize, total)

  return (
    <div className="space-y-4">
      <DataChangeLogFilters tableOptions={tableOptions} stats={stats} />

      <div className="rounded-md border">
        <Table>
          <TableHeader className="bg-muted/40">
            <TableRow>
              <TableHead>Table</TableHead>
              <TableHead>Record ID</TableHead>
              <TableHead>Action</TableHead>
              <TableHead>Changed By</TableHead>
              <TableHead>IP Address</TableHead>
              <TableHead>Time</TableHead>
              <TableHead className="w-12" />
            </TableRow>
          </TableHeader>
          <TableBody>
            {items.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="h-24 text-center text-muted-foreground">
                  No data change logs found.
                </TableCell>
              </TableRow>
            ) : (
              items.map((log) => (
                <Fragment key={log.id}>
                  <TableRow>
                    <TableCell>
                      <Badge variant="outline" className="font-mono text-xs">
                        {log.tableName}
                      </Badge>
                    </TableCell>
                    <TableCell className="font-mono text-xs">{log.recordId}</TableCell>
                    <TableCell>
                      <ActionBadge action={log.action} />
                    </TableCell>
                    <TableCell>
                      <div className="flex flex-col">
                        <span className="font-medium">{log.changedByName}</span>
                        <span className="text-xs text-muted-foreground">{log.changedBy}</span>
                      </div>
                    </TableCell>
                    <TableCell className="text-xs text-muted-foreground font-mono">
                      {log.ipAddress ?? "-"}
                    </TableCell>
                    <TableCell className="text-xs text-muted-foreground">
                      {formatDate(log.createdAt, "zh-CN")}
                    </TableCell>
                    <TableCell>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => setExpandedId(expandedId === log.id ? null : log.id)}
                      >
                        {expandedId === log.id ? "Hide" : "View"}
                      </Button>
                    </TableCell>
                  </TableRow>
                  {expandedId === log.id && (
                    <TableRow>
                      <TableCell colSpan={7} className="bg-muted/30">
                        <div className="grid gap-4 md:grid-cols-2">
                          <div>
                            <div className="mb-1 text-xs font-semibold text-muted-foreground">
                              Old Value
                            </div>
                            <pre className="max-h-60 overflow-auto rounded border bg-background p-2 text-xs">
                              {log.oldValue ?? "—"}
                            </pre>
                          </div>
                          <div>
                            <div className="mb-1 text-xs font-semibold text-muted-foreground">
                              New Value
                            </div>
                            <pre className="max-h-60 overflow-auto rounded border bg-background p-2 text-xs">
                              {log.newValue ?? "—"}
                            </pre>
                          </div>
                        </div>
                      </TableCell>
                    </TableRow>
                  )}
                </Fragment>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      <div className="flex items-center justify-between px-2 py-4">
        <div className="text-sm text-muted-foreground">
          {total > 0 ? (
            <>
              Showing <span className="font-medium">{start}</span>-
              <span className="font-medium">{end}</span> of{" "}
              <span className="font-medium">{total}</span> logs
            </>
          ) : (
            "No logs"
          )}
        </div>
        <div className="flex items-center space-x-2">
          <span className="text-sm font-medium">
            Page {page} of {Math.max(totalPages, 1)}
          </span>
          <Button
            variant="outline"
            className="h-8 w-8 p-0"
            onClick={() => handlePageChange(page - 1)}
            disabled={page <= 1}
          >
            <span className="sr-only">Previous page</span>
            <ChevronLeft className="h-4 w-4" />
          </Button>
          <Button
            variant="outline"
            className="h-8 w-8 p-0"
            onClick={() => handlePageChange(page + 1)}
            disabled={page >= totalPages}
          >
            <span className="sr-only">Next page</span>
            <ChevronRight className="h-4 w-4" />
          </Button>
        </div>
      </div>
    </div>
  )
}

function DataChangeLogFilters({
  tableOptions,
  stats,
}: {
  tableOptions: string[]
  stats: DataChangeStat[]
}) {
  const [tableName, setTableName] = useQueryState(
    "tableName",
    parseAsString.withOptions({ shallow: false })
  )
  const [action, setAction] = useQueryState(
    "action",
    parseAsString.withOptions({ shallow: false })
  )
  const [startDate, setStartDate] = useQueryState(
    "startDate",
    parseAsString.withOptions({ shallow: false })
  )
  const [endDate, setEndDate] = useQueryState(
    "endDate",
    parseAsString.withOptions({ shallow: false })
  )

  const hasFilters = Boolean(tableName || action || startDate || endDate)

  return (
    <div className="space-y-3">
      {stats.length > 0 && (
        <div className="flex flex-wrap gap-2">
          {stats.slice(0, 8).map((s) => (
            <Badge key={s.tableName} variant="secondary" className="gap-1">
              <span className="font-mono text-xs">{s.tableName}</span>
              <span className="text-xs text-muted-foreground">·</span>
              <span className="text-xs">{s.count}</span>
            </Badge>
          ))}
        </div>
      )}
      <div className="flex flex-col gap-3 md:flex-row md:items-center md:flex-wrap">
        <Select
          value={tableName || "all"}
          onValueChange={(val) => setTableName(val === "all" ? null : val)}
        >
          <SelectTrigger className="w-[180px] bg-background">
            <SelectValue placeholder="Table" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Any Table</SelectItem>
            {tableOptions.map((t) => (
              <SelectItem key={t} value={t}>
                {t}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        <Select
          value={action || "all"}
          onValueChange={(val) => setAction(val === "all" ? null : val)}
        >
          <SelectTrigger className="w-[140px] bg-background">
            <SelectValue placeholder="Action" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Any Action</SelectItem>
            <SelectItem value="create">Create</SelectItem>
            <SelectItem value="update">Update</SelectItem>
            <SelectItem value="delete">Delete</SelectItem>
          </SelectContent>
        </Select>

        <Input
          type="date"
          className="w-full md:w-[160px] bg-background"
          value={startDate || ""}
          onChange={(e) => setStartDate(e.target.value || null)}
        />
        <Input
          type="date"
          className="w-full md:w-[160px] bg-background"
          value={endDate || ""}
          onChange={(e) => setEndDate(e.target.value || null)}
        />

        {hasFilters && (
          <Button
            variant="ghost"
            onClick={() => {
              setTableName(null)
              setAction(null)
              setStartDate(null)
              setEndDate(null)
            }}
            className="h-10 px-3"
          >
            Reset
            <X className="ml-2 h-4 w-4" />
          </Button>
        )}
      </div>
    </div>
  )
}

function ActionBadge({ action }: { action: "create" | "update" | "delete" }) {
  const variant: BadgeProps["variant"] =
    action === "create" ? "default" : action === "update" ? "secondary" : "destructive"
  return (
    <Badge
      variant={variant}
      className={cn(
        "capitalize",
        action === "create" && "bg-green-600 hover:bg-green-700 border-transparent",
        action === "delete" && "bg-red-600 hover:bg-red-700 border-transparent"
      )}
    >
      {action}
    </Badge>
  )
}

export function DataChangeLogTable(props: DataChangeLogTableProps) {
  return (
    <Suspense fallback={null}>
      <DataChangeLogTableInner {...props} />
    </Suspense>
  )
}
