"use client";

import { useMemo } from "react";
import { ColumnMetadata } from "@/app/lib/api";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "./ui/dialog";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { Copy } from "lucide-react";
import { toast } from "sonner";

type Props = {
  open: boolean;
  onClose: () => void;
  row: Record<string, unknown> | null;
  columns: ColumnMetadata[];
};

function formatValue(value: unknown): string {
  if (value === null) return "NULL";
  if (value === undefined) return "";
  if (typeof value === "boolean") return value ? "true" : "false";
  if (typeof value === "object") {
    try {
      return JSON.stringify(value, null, 2);
    } catch {
      return "[object]";
    }
  }
  return String(value);
}

export default function RowDetailSheet({ open, onClose, row, columns }: Props) {
  const typeMap = useMemo(() => {
    const m = new Map<string, string>();
    for (const c of columns) {
      if (c.data_type) m.set(c.column_name, c.data_type);
    }
    return m;
  }, [columns]);

  const entries = useMemo(() => {
    if (!row) return [];
    if (columns.length > 0) {
      const ordered: [string, unknown][] = [];
      const seen = new Set<string>();
      for (const c of columns) {
        if (c.column_name in row) {
          ordered.push([c.column_name, row[c.column_name]]);
          seen.add(c.column_name);
        }
      }
      for (const [key, value] of Object.entries(row)) {
        if (!seen.has(key)) ordered.push([key, value]);
      }
      return ordered;
    }
    return Object.entries(row);
  }, [row, columns]);

  if (!row) return null;

  const copyAll = () => {
    navigator.clipboard.writeText(JSON.stringify(row, null, 2));
    toast.success("Copied row JSON to clipboard");
  };

  return (
    <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
      <DialogContent className="max-w-lg max-h-[85vh] overflow-hidden flex flex-col p-0">
        <div className="px-6 pt-6 pb-3">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              Row Detail
              <Badge variant="secondary" className="text-caption">
                {entries.length} fields
              </Badge>
            </DialogTitle>
            <DialogDescription>All values for this row</DialogDescription>
          </DialogHeader>
          <div className="flex justify-end mt-2">
            <Button
              variant="outline"
              size="sm"
              onClick={copyAll}
              className="h-7 text-body-sm"
            >
              <Copy className="h-3 w-3" /> Copy JSON
            </Button>
          </div>
        </div>
        <div className="flex-1 overflow-y-auto min-h-0 px-6 pb-6">
          <div className="divide-y divide-border/50">
            {entries.map(([key, value]) => {
              const formatted = formatValue(value);
              const isLong = formatted.length > 100 || formatted.includes("\n");
              return (
                <div key={key} className="py-2.5 group">
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-body-sm font-mono font-medium text-foreground">
                      {key}
                    </span>
                    <span className="text-tiny text-muted-foreground font-mono">
                      {typeMap.get(key) ?? ""}
                    </span>
                    <button
                      onClick={() => {
                        navigator.clipboard.writeText(formatted);
                        toast.success("Copied");
                      }}
                      className="ml-auto opacity-0 group-hover:opacity-100 transition-opacity text-muted-foreground hover:text-foreground"
                    >
                      <Copy className="h-3 w-3" />
                    </button>
                  </div>
                  {isLong ? (
                    <pre className="text-body-sm font-mono text-muted-foreground bg-muted/50 rounded p-2 overflow-auto max-h-[200px] whitespace-pre-wrap break-all">
                      {formatted}
                    </pre>
                  ) : (
                    <span
                      className={`text-body-sm font-mono ${value === null ? "text-muted-foreground/60 italic" : typeof value === "number" ? "text-primary tabular-nums" : typeof value === "boolean" ? "text-primary/80" : "text-foreground"}`}
                    >
                      {formatted}
                    </span>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
