import React, { useState, useEffect, useRef, useCallback } from "react";
import { RedisDetailPanel } from "./DetailPanel";
import { RefreshButton } from "./FilterBar";
import { redisQueryKeys, redisGetKeyDetail } from "./api";

function typeColor(type) {
  const colors = {
    string: "var(--green)",
    list: "var(--yellow)",
    set: "var(--purple)",
    zset: "var(--cyan)",
    hash: "#ff9f43",
    stream: "var(--red)",
  };
  return colors[type] || "var(--text-dim)";
}

const btnStyle = (enabled) => ({
  background: "none",
  border: "1px solid var(--border)",
  borderRadius: 4,
  padding: "2px 8px",
  color: enabled ? "var(--text)" : "var(--text-dim)",
  cursor: enabled ? "pointer" : "default",
  fontFamily: "inherit",
  fontSize: 11,
  opacity: enabled ? 1 : 0.4,
});

export default function RedisTabContent({ tab, updateTab, pageSize, setError, refreshKey, locked }) {
  const [selectedKey, setSelectedKey] = useState(null);
  const [detail, setDetail] = useState(null);
  const [detailLoading, setDetailLoading] = useState(false);
  const debounceRef = useRef(null);
  const pageSizeRef = useRef(pageSize);
  pageSizeRef.current = pageSize;
  const initialRefreshKey = useRef(refreshKey);

  // Auto-query on mount
  useEffect(() => {
    if (tab.results) return;
    runQuery(tab.filter || "*", 0);
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  // Refresh All
  useEffect(() => {
    if (refreshKey === initialRefreshKey.current) return;
    runQuery(tab.filter || "*", tab.page * pageSize);
  }, [refreshKey]); // eslint-disable-line react-hooks/exhaustive-deps

  const runQuery = useCallback((pattern, offset = 0) => {
    updateTab({ loading: true });
    setError(null);
    redisQueryKeys(tab.instanceId, { pattern: pattern || "*", offset, limit: pageSizeRef.current })
      .then((data) => {
        updateTab({
          results: data,
          loading: false,
        });
      })
      .catch((e) => {
        setError(e.message);
        updateTab({ loading: false });
      });
  }, [updateTab, setError]);

  const handleFilterChange = (value) => {
    updateTab({ filter: value });
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => {
      updateTab({ page: 0 });
      runQuery(value || "*", 0);
    }, 300);
  };

  const handleNextPage = () => {
    if (!tab.results?.has_more) return;
    const newPage = tab.page + 1;
    updateTab({ page: newPage });
    runQuery(tab.filter || "*", newPage * pageSize);
  };

  const handlePrevPage = () => {
    if (tab.page <= 0) return;
    const newPage = tab.page - 1;
    updateTab({ page: newPage });
    runQuery(tab.filter || "*", newPage * pageSize);
  };

  const handleSelectKey = (key) => {
    if (selectedKey === key) {
      setSelectedKey(null);
      setDetail(null);
      return;
    }
    setSelectedKey(key);
    setDetailLoading(true);
    setDetail(null);
    redisGetKeyDetail(tab.instanceId, key)
      .then((data) => { setDetail(data); setDetailLoading(false); })
      .catch((e) => { setError(e.message); setDetailLoading(false); });
  };

  const rows = tab.results?.rows;
  const totalCount = tab.results?.total_count || 0;
  const hasMore = tab.results?.has_more || false;
  const columns = rows && rows.length > 0 ? Object.keys(rows[0]) : [];

  return (
    <div style={{ display: "flex", flex: 1, overflow: "hidden" }}>
      <div style={{ display: "flex", flexDirection: "column", flex: 1, overflow: "hidden" }}>
        {/* Filter bar */}
        {tab.filtersVisible !== false && (
          <div
            style={{
              display: "flex",
              gap: 12,
              padding: "12px 20px",
              background: "var(--panel)",
              borderBottom: "1px solid var(--border)",
              alignItems: "flex-end",
            }}
          >
            <div style={{ flex: 1 }}>
              <label
                style={{
                  display: "block",
                  fontSize: 10,
                  fontWeight: 600,
                  textTransform: "uppercase",
                  letterSpacing: "0.1em",
                  color: "var(--green)",
                  marginBottom: 4,
                }}
              >
                Filter keys
              </label>
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  background: "var(--green-bg)",
                  border: "1px solid var(--green)33",
                  borderRadius: 6,
                }}
              >
                <input
                  type="text"
                  value={tab.filter || ""}
                  onChange={(e) => handleFilterChange(e.target.value)}
                  placeholder="pattern (e.g. user:*, session:abc*, *config*)"
                  spellCheck={false}
                  style={{
                    flex: 1,
                    background: "transparent",
                    border: "none",
                    padding: "8px 12px",
                    color: "var(--text)",
                    fontFamily: "inherit",
                    fontSize: 13,
                    outline: "none",
                  }}
                  onFocus={(e) => { e.target.closest("div").style.borderColor = "var(--green)66"; }}
                  onBlur={(e) => { e.target.closest("div").style.borderColor = "var(--green)33"; }}
                />
              </div>
              <div style={{ fontSize: 10, color: "var(--text-dim)", marginTop: 4 }}>
                Supports glob patterns: * ? [abc]. Plain text auto-wraps as *text*.
              </div>
            </div>
            <RefreshButton onClick={() => runQuery(tab.filter || "*", tab.page * pageSize)} />
          </div>
        )}

        {/* Results */}
        {rows !== null && rows !== undefined && (
          <div style={{ flex: 1, overflow: "auto", position: "relative" }}>
            <div
              style={{
                padding: "8px 20px",
                fontSize: 11,
                color: "var(--text-dim)",
                borderBottom: "1px solid var(--border)",
                background: "var(--panel)",
                position: "sticky",
                top: 0,
                zIndex: 10,
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
              }}
            >
              <span>
                {totalCount} keys{tab.filter ? ` matching "${tab.filter}"` : ""}
                {totalCount > pageSize ? ` (showing ${tab.page * pageSize + 1}–${Math.min((tab.page + 1) * pageSize, totalCount)})` : ""}
              </span>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              {locked && (
                <button
                  onClick={() => updateTab({ filtersVisible: tab.filtersVisible === false ? true : false })}
                  title={tab.filtersVisible !== false ? "Hide filters" : "Show filters"}
                  style={{
                    background: tab.filtersVisible !== false ? "rgba(255,255,255,0.04)" : "none",
                    border: "1px solid var(--border)",
                    borderRadius: 4,
                    color: tab.filtersVisible !== false ? "var(--text)" : "var(--text-dim)",
                    fontSize: 10,
                    padding: "1px 6px",
                    cursor: "pointer",
                    display: "flex",
                    alignItems: "center",
                    gap: 3,
                  }}
                  onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--text-dim)"; }}
                  onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--border)"; }}
                >
                  <span style={{ fontSize: 8 }}>{tab.filtersVisible !== false ? "\u25BE" : "\u25B8"}</span>
                  <span>filters</span>
                </button>
              )}
              {(hasMore || tab.page > 0) && (
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <button style={btnStyle(tab.page > 0)} disabled={tab.page <= 0} onClick={handlePrevPage}>Prev</button>
                  <span>Page {tab.page + 1} of {Math.ceil(totalCount / pageSize)}</span>
                  <button style={btnStyle(hasMore)} disabled={!hasMore} onClick={handleNextPage}>Next</button>
                </div>
              )}
              </div>
            </div>

            {rows.length === 0 ? (
              <div style={{ padding: 40, textAlign: "center", color: "var(--text-dim)" }}>No keys found</div>
            ) : (
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
                <thead>
                  <tr>
                    {columns.map((col) => (
                      <th
                        key={col}
                        style={{
                          position: "sticky",
                          top: 33,
                          background: "var(--bg)",
                          padding: "8px 12px",
                          textAlign: "left",
                          fontWeight: 600,
                          fontSize: 11,
                          textTransform: "uppercase",
                          letterSpacing: "0.05em",
                          color: "var(--text-dim)",
                          borderBottom: "1px solid var(--border)",
                          whiteSpace: "nowrap",
                          zIndex: 5,
                        }}
                      >
                        {col}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {rows.map((row, i) => {
                    const isSelected = selectedKey === row.key;
                    return (
                      <tr
                        key={row.key}
                        onClick={() => handleSelectKey(row.key)}
                        style={{
                          cursor: "pointer",
                          background: isSelected ? "var(--selected-row)" : i % 2 === 1 ? "var(--row-alt)" : "transparent",
                          borderLeft: isSelected ? "3px solid var(--purple)" : "3px solid transparent",
                        }}
                        onMouseEnter={(e) => { if (!isSelected) e.currentTarget.style.background = "var(--row-hover)"; }}
                        onMouseLeave={(e) => {
                          e.currentTarget.style.background = isSelected ? "var(--selected-row)" : i % 2 === 1 ? "var(--row-alt)" : "transparent";
                        }}
                      >
                        {columns.map((col) => (
                          <td
                            key={col}
                            style={{
                              padding: "6px 12px",
                              borderBottom: "1px solid var(--border)",
                              whiteSpace: "nowrap",
                              maxWidth: 500,
                              overflow: "hidden",
                              textOverflow: "ellipsis",
                            }}
                          >
                            {col === "type" ? (
                              <span style={{
                                color: typeColor(row[col]),
                                background: typeColor(row[col]) + "15",
                                padding: "1px 6px",
                                borderRadius: 3,
                                fontSize: 10,
                                fontWeight: 600,
                              }}>
                                {row[col]}
                              </span>
                            ) : (
                              String(row[col])
                            )}
                          </td>
                        ))}
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            )}
          </div>
        )}
      </div>

      {selectedKey && (
        <RedisDetailPanel
          detail={detail}
          loading={detailLoading}
          onClose={() => { setSelectedKey(null); setDetail(null); }}
        />
      )}
    </div>
  );
}
