import { useState, useEffect, useCallback } from "react";
import { apiClient } from "@/utils/apiClient";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Loader2, ChevronLeft, ChevronRight, Eye, Search, ChevronDown, ChevronRight as ChevronRightIcon, Copy, Check } from "lucide-react";

interface AuditEntry {
  id: number;
  user_id: number;
  username: string | null;
  success: boolean;
  error_message: string | null;
  duration_ms: number | null;
  created_at: string;
  target_endpoint: string | null;
  // Import-specific
  product_count?: number;
  environment?: string;
  created_count?: number;
  errored_count?: number;
  // Editor-specific
  pid?: number;
  product_name?: string | null;
  action?: string;
}

interface AuditDetail extends AuditEntry {
  request_payload: unknown;
  response_payload: unknown;
  // Import-specific
  use_test_data_source?: boolean;
  session_id?: number | null;
}

type LogType = "editor" | "import";

const PAGE_SIZE = 25;

const ACTION_LABELS: Record<string, string> = {
  product_edit: "Product Edit",
  image_changes: "Image Changes",
  taxonomy_set: "Taxonomy Set",
};

function formatDate(iso: string): string {
  const d = new Date(iso);
  return d.toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
    hour: "numeric",
    minute: "2-digit",
  });
}

function formatDuration(ms: number | null): string {
  if (ms === null) return "-";
  if (ms < 1000) return `${ms}ms`;
  return `${(ms / 1000).toFixed(1)}s`;
}

export function AuditLog() {
  const [logType, setLogType] = useState<LogType>("editor");
  const [entries, setEntries] = useState<AuditEntry[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(0);
  const [isLoading, setIsLoading] = useState(false);
  const [detail, setDetail] = useState<AuditDetail | null>(null);
  const [isLoadingDetail, setIsLoadingDetail] = useState(false);

  // Filters
  const [filterPid, setFilterPid] = useState("");
  const [filterSuccess, setFilterSuccess] = useState<string>("all");
  const [filterAction, setFilterAction] = useState<string>("all");

  const baseUrl = logType === "editor" ? "/api/product-editor-audit-log" : "/api/import-audit-log";

  const fetchEntries = useCallback(async () => {
    setIsLoading(true);
    try {
      const params: Record<string, string | number> = {
        limit: PAGE_SIZE,
        offset: page * PAGE_SIZE,
      };
      if (filterSuccess !== "all") params.success = filterSuccess;
      if (logType === "editor") {
        if (filterPid.trim()) params.pid = filterPid.trim();
        if (filterAction !== "all") params.action = filterAction;
      }
      const res = await apiClient.get(baseUrl, { params });
      setEntries(res.data.entries);
      setTotal(res.data.total);
    } catch {
      setEntries([]);
      setTotal(0);
    } finally {
      setIsLoading(false);
    }
  }, [baseUrl, page, filterSuccess, filterPid, filterAction, logType]);

  useEffect(() => {
    fetchEntries();
  }, [fetchEntries]);

  // Reset page when filters or log type change
  useEffect(() => {
    setPage(0);
  }, [filterSuccess, filterPid, filterAction, logType]);

  const handleTabChange = (val: string) => {
    setLogType(val as LogType);
    setFilterPid("");
    setFilterSuccess("all");
    setFilterAction("all");
    setEntries([]);
    setTotal(0);
    setDetail(null);
  };

  const viewDetail = async (id: number) => {
    setIsLoadingDetail(true);
    try {
      const res = await apiClient.get(`${baseUrl}/${id}`);
      setDetail(res.data);
    } catch {
      setDetail(null);
    } finally {
      setIsLoadingDetail(false);
    }
  };

  const totalPages = Math.ceil(total / PAGE_SIZE);

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-2xl font-bold">Audit Log</h2>
        <p className="text-muted-foreground text-sm mt-1">
          View API call history for product imports and editor changes.
        </p>
      </div>

      <Tabs value={logType} onValueChange={handleTabChange}>
        <TabsList>
          <TabsTrigger value="editor">Product Editor</TabsTrigger>
          <TabsTrigger value="import">Product Import</TabsTrigger>
        </TabsList>

        <TabsContent value="editor" className="mt-4">
          <Filters
            filterPid={filterPid}
            onFilterPidChange={setFilterPid}
            filterSuccess={filterSuccess}
            onFilterSuccessChange={setFilterSuccess}
            filterAction={filterAction}
            onFilterActionChange={setFilterAction}
            showPidFilter
            showActionFilter
          />
        </TabsContent>
        <TabsContent value="import" className="mt-4">
          <Filters
            filterPid=""
            onFilterPidChange={() => {}}
            filterSuccess={filterSuccess}
            onFilterSuccessChange={setFilterSuccess}
            filterAction=""
            onFilterActionChange={() => {}}
            showPidFilter={false}
            showActionFilter={false}
          />
        </TabsContent>
      </Tabs>

      <Card>
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <CardTitle className="text-base">
              {total} {total === 1 ? "entry" : "entries"}
            </CardTitle>
            <div className="flex items-center gap-2">
              <Button
                variant="outline"
                size="sm"
                disabled={page === 0}
                onClick={() => setPage((p) => p - 1)}
              >
                <ChevronLeft className="h-4 w-4" />
              </Button>
              <span className="text-sm text-muted-foreground">
                {totalPages > 0 ? `${page + 1} / ${totalPages}` : "0 / 0"}
              </span>
              <Button
                variant="outline"
                size="sm"
                disabled={page >= totalPages - 1}
                onClick={() => setPage((p) => p + 1)}
              >
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
            </div>
          ) : entries.length === 0 ? (
            <p className="text-center text-muted-foreground py-12">No entries found.</p>
          ) : logType === "editor" ? (
            <EditorTable entries={entries} onView={viewDetail} />
          ) : (
            <ImportTable entries={entries} onView={viewDetail} />
          )}
        </CardContent>
      </Card>

      <Dialog open={detail !== null} onOpenChange={(open) => { if (!open) setDetail(null); }}>
        <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
          {isLoadingDetail ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="h-6 w-6 animate-spin" />
            </div>
          ) : detail ? (
            <>
              <DialogHeader>
                <DialogTitle className="flex items-center gap-2">
                  Entry #{detail.id}
                  <SuccessBadge success={detail.success} />
                </DialogTitle>
              </DialogHeader>
              <DetailView detail={detail} logType={logType} />
            </>
          ) : null}
        </DialogContent>
      </Dialog>
    </div>
  );
}

// --- Sub-components ---

function Filters({
  filterPid,
  onFilterPidChange,
  filterSuccess,
  onFilterSuccessChange,
  filterAction,
  onFilterActionChange,
  showPidFilter,
  showActionFilter,
}: {
  filterPid: string;
  onFilterPidChange: (v: string) => void;
  filterSuccess: string;
  onFilterSuccessChange: (v: string) => void;
  filterAction: string;
  onFilterActionChange: (v: string) => void;
  showPidFilter: boolean;
  showActionFilter: boolean;
}) {
  return (
    <div className="flex items-center gap-3 flex-wrap">
      {showPidFilter && (
        <div className="relative">
          <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="Filter by PID..."
            value={filterPid}
            onChange={(e) => onFilterPidChange(e.target.value)}
            className="pl-8 w-40"
          />
        </div>
      )}
      <Select value={filterSuccess} onValueChange={onFilterSuccessChange}>
        <SelectTrigger className="w-36">
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="all">All results</SelectItem>
          <SelectItem value="true">Success only</SelectItem>
          <SelectItem value="false">Failures only</SelectItem>
        </SelectContent>
      </Select>
      {showActionFilter && (
        <Select value={filterAction} onValueChange={onFilterActionChange}>
          <SelectTrigger className="w-40">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All actions</SelectItem>
            <SelectItem value="product_edit">Product Edit</SelectItem>
            <SelectItem value="image_changes">Image Changes</SelectItem>
            <SelectItem value="taxonomy_set">Taxonomy Set</SelectItem>
          </SelectContent>
        </Select>
      )}
    </div>
  );
}

function SuccessBadge({ success }: { success: boolean }) {
  return success ? (
    <Badge variant="outline" className="text-green-600 border-green-300 bg-green-50 dark:bg-green-950 dark:border-green-800 dark:text-green-400">
      Success
    </Badge>
  ) : (
    <Badge variant="outline" className="text-red-600 border-red-300 bg-red-50 dark:bg-red-950 dark:border-red-800 dark:text-red-400">
      Failed
    </Badge>
  );
}

function EditorTable({ entries, onView }: { entries: AuditEntry[]; onView: (id: number) => void }) {
  return (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead className="w-[140px]">Time</TableHead>
          <TableHead>User</TableHead>
          <TableHead>Product</TableHead>
          <TableHead>Action</TableHead>
          <TableHead>Status</TableHead>
          <TableHead>Duration</TableHead>
          <TableHead className="w-[50px]" />
        </TableRow>
      </TableHeader>
      <TableBody>
        {entries.map((e) => (
          <TableRow key={e.id}>
            <TableCell className="text-xs text-muted-foreground">{formatDate(e.created_at)}</TableCell>
            <TableCell>{e.username ?? `#${e.user_id}`}</TableCell>
            <TableCell>
              <div className="flex flex-col">
                <a
                  href={`https://backend.acherryontop.com/product/${e.pid}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="font-mono text-sm hover:underline text-blue-600 dark:text-blue-400"
                >
                  {e.pid}
                </a>
                {e.product_name && (
                  <span className="text-xs text-muted-foreground truncate max-w-[200px]">{e.product_name}</span>
                )}
              </div>
            </TableCell>
            <TableCell>
              <Badge variant="secondary" className="font-normal">
                {ACTION_LABELS[e.action ?? ""] ?? e.action}
              </Badge>
            </TableCell>
            <TableCell><SuccessBadge success={e.success} /></TableCell>
            <TableCell className="text-xs text-muted-foreground">{formatDuration(e.duration_ms)}</TableCell>
            <TableCell>
              <Button variant="ghost" size="icon" onClick={() => onView(e.id)} title="View details">
                <Eye className="h-4 w-4" />
              </Button>
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  );
}

function ImportTable({ entries, onView }: { entries: AuditEntry[]; onView: (id: number) => void }) {
  return (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead className="w-[140px]">Time</TableHead>
          <TableHead>User</TableHead>
          <TableHead>Products</TableHead>
          <TableHead>Env</TableHead>
          <TableHead>Status</TableHead>
          <TableHead>Created / Errored</TableHead>
          <TableHead>Duration</TableHead>
          <TableHead className="w-[50px]" />
        </TableRow>
      </TableHeader>
      <TableBody>
        {entries.map((e) => (
          <TableRow key={e.id}>
            <TableCell className="text-xs text-muted-foreground">{formatDate(e.created_at)}</TableCell>
            <TableCell>{e.username ?? `#${e.user_id}`}</TableCell>
            <TableCell>{e.product_count}</TableCell>
            <TableCell>
              <Badge variant={e.environment === "prod" ? "default" : "secondary"} className="font-normal">
                {e.environment}
              </Badge>
            </TableCell>
            <TableCell><SuccessBadge success={e.success} /></TableCell>
            <TableCell className="text-xs">
              {e.created_count ?? 0} / {e.errored_count ?? 0}
            </TableCell>
            <TableCell className="text-xs text-muted-foreground">{formatDuration(e.duration_ms)}</TableCell>
            <TableCell>
              <Button variant="ghost" size="icon" onClick={() => onView(e.id)} title="View details">
                <Eye className="h-4 w-4" />
              </Button>
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  );
}

function DetailView({ detail, logType }: { detail: AuditDetail; logType: LogType }) {
  return (
    <div className="space-y-4 text-sm">
      <div className="grid grid-cols-2 gap-x-6 gap-y-2">
        <div>
          <span className="text-muted-foreground">User</span>
          <p className="font-medium">{detail.username ?? `#${detail.user_id}`}</p>
        </div>
        <div>
          <span className="text-muted-foreground">Time</span>
          <p className="font-medium">{new Date(detail.created_at).toLocaleString()}</p>
        </div>
        {logType === "editor" && (
          <>
            <div>
              <span className="text-muted-foreground">Product</span>
              <p className="font-medium">
                <a
                  href={`https://backend.acherryontop.com/product/${detail.pid}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="font-mono hover:underline text-blue-600 dark:text-blue-400"
                >
                  {detail.pid}
                </a>
                {detail.product_name && (
                  <span className="ml-2 font-sans text-muted-foreground">{detail.product_name}</span>
                )}
              </p>
            </div>
            <div>
              <span className="text-muted-foreground">Action</span>
              <p className="font-medium">{ACTION_LABELS[detail.action ?? ""] ?? detail.action}</p>
            </div>
          </>
        )}
        {logType === "import" && (
          <>
            <div>
              <span className="text-muted-foreground">Product Count</span>
              <p className="font-medium">{detail.product_count}</p>
            </div>
            <div>
              <span className="text-muted-foreground">Environment</span>
              <p className="font-medium">{detail.environment}</p>
            </div>
            <div>
              <span className="text-muted-foreground">Created / Errored</span>
              <p className="font-medium">{detail.created_count ?? 0} / {detail.errored_count ?? 0}</p>
            </div>
          </>
        )}
        <div>
          <span className="text-muted-foreground">Endpoint</span>
          <p className="font-medium font-mono text-xs break-all">{detail.target_endpoint ?? "-"}</p>
        </div>
        <div>
          <span className="text-muted-foreground">Duration</span>
          <p className="font-medium">{formatDuration(detail.duration_ms)}</p>
        </div>
      </div>

      {detail.error_message && (
        <div>
          <span className="text-muted-foreground">Error</span>
          <p className="text-red-600 dark:text-red-400 mt-1 text-xs bg-red-50 dark:bg-red-950 p-2 rounded-md break-all">
            {detail.error_message}
          </p>
        </div>
      )}

      <RequestPayloadSection payload={detail.request_payload} />

      {detail.response_payload != null && (
        <PayloadSection label="Response Payload" data={detail.response_payload} />
      )}
    </div>
  );
}

/** Keys in request_payload that were NOT sent to the API — stored for audit context only */
const CONTEXT_ONLY_KEYS = new Set(["previous_values", "previous_ids"]);

function RequestPayloadSection({ payload }: { payload: unknown }) {
  const parsed = typeof payload === "string" ? (() => { try { return JSON.parse(payload); } catch { return payload; } })() : payload;

  // Extract context-only keys from the payload
  let apiPayload = parsed;
  let contextData: Record<string, unknown> | null = null;

  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
    const obj = parsed as Record<string, unknown>;
    const contextEntries = Object.entries(obj).filter(([k]) => CONTEXT_ONLY_KEYS.has(k));
    if (contextEntries.length > 0) {
      const remaining = Object.fromEntries(Object.entries(obj).filter(([k]) => !CONTEXT_ONLY_KEYS.has(k)));
      apiPayload = remaining;
      contextData = Object.fromEntries(contextEntries);
    }
  }

  return (
    <>
      <PayloadSection label="Request Payload" data={apiPayload} />
      {contextData && (
        <PayloadSection label="Previous Values" data={contextData} />
      )}
    </>
  );
}

// --- Formatted JSON viewer ---

/** Unwrap double-encoded JSON strings from JSONB columns */
function parsePayload(raw: unknown): unknown {
  if (typeof raw === "string") {
    try { return JSON.parse(raw); } catch { return raw; }
  }
  return raw;
}

function PayloadSection({ label, data: rawData }: { label: string; data: unknown }) {
  const data = parsePayload(rawData);
  const [showRaw, setShowRaw] = useState(false);
  const [copied, setCopied] = useState(false);

  const copyJson = () => {
    navigator.clipboard.writeText(JSON.stringify(data, null, 2));
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };

  return (
    <div className="min-w-0">
      <div className="flex items-center justify-between mb-1">
        <span className="text-muted-foreground">{label}</span>
        <div className="flex items-center gap-1 shrink-0">
          <Button variant="ghost" size="sm" className="h-6 px-2 text-xs" onClick={() => setShowRaw((v) => !v)}>
            {showRaw ? "Formatted" : "Raw JSON"}
          </Button>
          <Button variant="ghost" size="icon" className="h-6 w-6" onClick={copyJson} title="Copy JSON">
            {copied ? <Check className="h-3 w-3 text-green-500" /> : <Copy className="h-3 w-3" />}
          </Button>
        </div>
      </div>
      {showRaw ? (
        <pre className="p-3 bg-muted rounded-md text-xs max-h-72 overflow-y-auto font-mono whitespace-pre-wrap break-words">
          {JSON.stringify(data, null, 2)}
        </pre>
      ) : (
        <div className="p-3 bg-muted rounded-md text-xs max-h-72 overflow-y-auto">
          <JsonValue value={data} depth={0} />
        </div>
      )}
    </div>
  );
}

function JsonValue({ value, depth }: { value: unknown; depth: number }) {
  if (value === null || value === undefined) {
    return <span className="text-muted-foreground italic">null</span>;
  }

  if (typeof value === "boolean") {
    return <span className={value ? "text-green-600 dark:text-green-400" : "text-red-600 dark:text-red-400"}>{String(value)}</span>;
  }

  if (typeof value === "number") {
    return <span className="text-blue-600 dark:text-blue-400">{value}</span>;
  }

  if (typeof value === "string") {
    return <JsonString value={value} />;
  }

  if (Array.isArray(value)) {
    return <JsonArray items={value} depth={depth} />;
  }

  if (typeof value === "object") {
    return <JsonObject obj={value as Record<string, unknown>} depth={depth} />;
  }

  return <span>{String(value)}</span>;
}

const STRING_TRUNCATE_LIMIT = 1000;

function JsonString({ value }: { value: string }) {
  const [expanded, setExpanded] = useState(false);

  if (value.length <= STRING_TRUNCATE_LIMIT || expanded) {
    return (
      <span className="text-amber-700 dark:text-amber-400 break-words whitespace-pre-wrap">
        {value}
        {expanded && value.length > STRING_TRUNCATE_LIMIT && (
          <button onClick={() => setExpanded(false)} className="ml-1 text-muted-foreground hover:text-foreground text-[10px] underline">
            show less
          </button>
        )}
      </span>
    );
  }

  return (
    <span className="text-amber-700 dark:text-amber-400 break-words whitespace-pre-wrap">
      {value.slice(0, STRING_TRUNCATE_LIMIT)}
      <span className="text-muted-foreground">... </span>
      <button onClick={() => setExpanded(true)} className="text-muted-foreground hover:text-foreground text-[10px] underline">
        show all ({value.length} chars)
      </button>
    </span>
  );
}

function JsonObject({ obj, depth }: { obj: Record<string, unknown>; depth: number }) {
  const entries = Object.entries(obj);

  if (entries.length === 0) {
    return <span className="text-muted-foreground">{"{}"}</span>;
  }

  // For shallow objects with only primitive values, show inline
  const allPrimitive = entries.every(([, v]) => v === null || typeof v !== "object");
  if (allPrimitive && entries.length <= 4) {
    return (
      <span className="inline">
        {"{ "}
        {entries.map(([k, v], i) => (
          <span key={k}>
            <span className="text-purple-600 dark:text-purple-400">{k}</span>
            <span className="text-muted-foreground">: </span>
            <JsonValue value={v} depth={depth + 1} />
            {i < entries.length - 1 && <span className="text-muted-foreground">, </span>}
          </span>
        ))}
        {" }"}
      </span>
    );
  }

  return (
    <div className="space-y-1">
      {entries.map(([key, val]) => (
        <JsonField key={key} fieldKey={key} value={val} depth={depth} />
      ))}
    </div>
  );
}

/** Renders a single key-value pair. Nested objects/arrays use the key as a collapsible label. */
function JsonField({ fieldKey, value, depth }: { fieldKey: string; value: unknown; depth: number; expanded?: boolean }) {
  const [open, setOpen] = useState(depth < 1);
  const isNestedObj = value !== null && typeof value === "object" && !Array.isArray(value) && Object.keys(value as object).length > 0;
  const isNestedArr = Array.isArray(value) && value.length > 0 && !value.every((v) => v === null || typeof v !== "object");

  if (isNestedObj || isNestedArr) {
    return (
      <div>
        <button
          onClick={() => setOpen((v) => !v)}
          className="inline-flex items-center gap-1 hover:text-foreground"
        >
          {open ? <ChevronDown className="h-3 w-3 text-muted-foreground" /> : <ChevronRightIcon className="h-3 w-3 text-muted-foreground" />}
          <span className="text-purple-600 dark:text-purple-400 font-medium">{fieldKey}</span>
        </button>
        {open && (
          <div className="ml-4 border-l border-border pl-3 mt-1">
            <JsonValue value={value} depth={depth + 1} />
          </div>
        )}
      </div>
    );
  }

  // Primitive or small array — render inline
  return (
    <div>
      <span className="text-purple-600 dark:text-purple-400 font-medium">{fieldKey}</span>
      <span className="text-muted-foreground">: </span>
      <JsonValue value={value} depth={depth + 1} />
    </div>
  );
}

function JsonArray({ items, depth }: { items: unknown[]; depth: number }) {
  if (items.length === 0) {
    return <span className="text-muted-foreground">[]</span>;
  }

  // Small arrays of primitives — show inline
  const allPrimitive = items.every((v) => v === null || typeof v !== "object");
  if (allPrimitive && items.length <= 10) {
    return (
      <span className="inline">
        {"["}
        {items.map((v, i) => (
          <span key={i}>
            <JsonValue value={v} depth={depth + 1} />
            {i < items.length - 1 && <span className="text-muted-foreground">, </span>}
          </span>
        ))}
        {"]"}
      </span>
    );
  }

  // Arrays of objects — render each item as a collapsible block
  const hasObjects = items.some((v) => v !== null && typeof v === "object");
  if (hasObjects) {
    return (
      <div className="space-y-1">
        {items.map((item, i) => (
          <JsonArrayItem key={i} index={i} value={item} depth={depth} />
        ))}
      </div>
    );
  }

  return (
    <div className="space-y-1">
      {items.map((item, i) => (
        <div key={i}>
          <span className="text-muted-foreground mr-1">[{i}]</span>
          <JsonValue value={item} depth={depth + 1} />
        </div>
      ))}
    </div>
  );
}

function JsonArrayItem({ index, value, depth }: { index: number; value: unknown; depth: number }) {
  const [open, setOpen] = useState(true);
  const isObject = value !== null && typeof value === "object";

  if (!isObject) {
    return (
      <div>
        <span className="text-muted-foreground mr-1">[{index}]</span>
        <JsonValue value={value} depth={depth + 1} />
      </div>
    );
  }

  return (
    <div>
      <button
        onClick={() => setOpen((v) => !v)}
        className="inline-flex items-center gap-1 hover:text-foreground"
      >
        {open ? <ChevronDown className="h-3 w-3 text-muted-foreground" /> : <ChevronRightIcon className="h-3 w-3 text-muted-foreground" />}
        <span className="text-muted-foreground font-medium">[{index}]</span>
      </button>
      {open && (
        <div className="ml-4 border-l border-border pl-3 mt-1">
          <JsonValue value={value} depth={depth + 1} />
        </div>
      )}
    </div>
  );
}
