
import { useState, useEffect } from "react";

type DataTableProps = {
  id: string;
  headers: string[];
  onChange: (data: string[][]) => void;
};

const TOTAL_MARKETING_STATUS_OPTIONS = [
  { value: "NEW", label: "NEW" },
  { value: "EXISTING", label: "EXISTING" },
];

// Helper: Indian number format (e.g., 3,00,000)
function formatIndianAmount(value: string): string {
  // Remove non-digit except dot
  let [intPart, decPart] = value.replace(/[^0-9.]/g, "").split(".");
  if (!intPart) intPart = "0";
  let lastThree = intPart.slice(-3);
  let otherNumbers = intPart.slice(0, -3);
  if (otherNumbers !== "") {
    lastThree = "," + lastThree;
  }
  let formatted =
    otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;
  if (decPart !== undefined) {
    formatted += "." + decPart.slice(0, 2);
  }
  return formatted.replace(/^,/, "");
}

// Helper: Email validation
function isValidEmail(email: string): boolean {
  // Simple regex for email validation
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

export default function DataTable({ id, headers, onChange }: DataTableProps) {
  const [rows, setRows] = useState<string[][]>([Array(headers.length).fill("")]);
  const [showAction, setShowAction] = useState(false);
  const [emailError, setEmailError] = useState<{ row: number; col: number; value: string } | null>(null);

  useEffect(() => {
    const saved = localStorage.getItem(`saved-${id}`);
    if (saved) {
      const parsed = JSON.parse(saved);
      const age = Date.now() - parsed.timestamp;
      if (
        age < 3 * 60 * 60 * 1000 &&
        Array.isArray(parsed.data) &&
        parsed.data.length > 0 &&
        !(
          parsed.data.length === 1 &&
          parsed.data[0].every((cell: string) => cell === "")
        )
      ) {
        setRows(parsed.data);
        onChange(parsed.data);
        if (parsed.data.length > 1) setShowAction(true);
      }
    }
  }, []);

  const saveData = () => {
    // Email validation: check all email columns before saving
    for (let i = 0; i < rows.length; i++) {
      for (let j = 0; j < headers.length; j++) {
        if (headers[j].toLowerCase().includes("email")) {
          const email = rows[i][j];
          if (email && !isValidEmail(email)) {
            setEmailError({ row: i, col: j, value: email });
            return;
          }
        }
      }
    }
    setEmailError(null);

    const notAllEmpty =
      rows.length > 1 ||
      (rows.length === 1 && rows[0].some((cell) => cell.trim() !== ""));
    if (notAllEmpty) {
      localStorage.setItem(
        `saved-${id}`,
        JSON.stringify({
          data: rows,
          timestamp: Date.now(),
        })
      );
      alert("Saved successfully!");
    } else {
      localStorage.removeItem(`saved-${id}`);
      alert("No data to save.");
    }
  };

  // Only convert to uppercase for text input, not for dropdowns
  // Add: auto-format for amount columns, and email validation on blur
  const updateRow = (
    i: number,
    j: number,
    value: string,
    isDropdown: boolean = false,
    isAmount: boolean = false,
    isEmail: boolean = false
  ) => {
    const updated = [...rows];
    if (isDropdown) {
      updated[i][j] = value;
    } else if (isAmount) {
      // Remove commas, allow only numbers and dot, then format
      const raw = value.replace(/,/g, "");
      updated[i][j] = formatIndianAmount(raw);
    } else if (isEmail) {
      updated[i][j] = value;
    } else {
      updated[i][j] = value.toUpperCase();
    }
    setRows(updated);
    onChange(updated);
    if (!showAction) setShowAction(true);
  };

  const handleEmailBlur = (i: number, j: number, value: string) => {
    if (value && !isValidEmail(value)) {
      setEmailError({ row: i, col: j, value });
    } else {
      setEmailError(null);
    }
  };

  const addRow = () => {
    const updated = [...rows, Array(headers.length).fill("")];
    setRows(updated);
    onChange(updated);
    setShowAction(true);
  };

  const deleteRow = (i: number) => {
    if (rows.length === 1) return;
    const updated = rows.filter((_, idx) => idx !== i);
    setRows(updated);
    onChange(updated);
    if (updated.length === 1 && updated[0].every(cell => cell === "")) {
      localStorage.removeItem(`saved-${id}`);
      setShowAction(false);
    }
  };

  const typeOfWorkOptions = [
    "DIGITAL PRINTING",
    "OFFSET PRINTING",
    "GIFTS",
    "SIGNAGES",
    "BRANDING",
    "REPROGRAPHICS",
    "OTHERS",
  ];

  // Detect if this is the Total Marketing table (for status dropdown)
  const isTotalMarketingTable =
    headers.length >= 2 &&
    headers[1].toLowerCase() === "status" &&
    id.toLowerCase().includes("total-marketing");

  // Detect amount columns (case-insensitive, e.g., "Amount", "Invoice Amount", "SO Amount", "Received Amount", "SO VALUE", "INVOICE VALUE")
  const isAmountColumn = (header: string) =>
    /amount|amt|received amount|rcvd amount|so value|invoice value/i.test(header);

  // Detect email columns
  const isEmailColumn = (header: string) =>
    /email/i.test(header);

  return (
    <div>
      <table id={id} className="container">
        <thead>
          <tr>
            {headers.map((h, i) => <th key={i}>{h}</th>)}
            {showAction && <th>Action</th>}
          </tr>
        </thead>
        <tbody>
          {rows.map((row, i) => (
            <tr key={i}>
              {row.map((cell, j) => {
                // For "Type of Work" column, show dropdown
                if (headers[j].toUpperCase() === "TYPE OF WORK") {
                  return (
                    <td key={j} data-label={headers[j]}>
                      <select
                        value={cell}
                        onChange={(e) => updateRow(i, j, e.target.value, true)}
                        className="input-responsive"
                      >
                        <option value="">SELECT TYPE</option>
                        {typeOfWorkOptions.map((option) => (
                          <option key={option} value={option}>
                            {option}
                          </option>
                        ))}
                      </select>
                    </td>
                  );
                }
                // For "Status" column in Total Marketing, show dropdown
                if (
                  isTotalMarketingTable &&
                  headers[j].toLowerCase() === "status"
                ) {
                  return (
                    <td key={j} data-label={headers[j]}>
                      <select
                        value={cell}
                        onChange={(e) => updateRow(i, j, e.target.value, true)}
                        className="input-responsive"
                      >
                        <option value="">SELECT STATUS</option>
                        {TOTAL_MARKETING_STATUS_OPTIONS.map((option) => (
                          <option key={option.value} value={option.value}>
                            {option.label}
                          </option>
                        ))}
                      </select>
                    </td>
                  );
                }
                // For amount columns, auto-format
                if (isAmountColumn(headers[j])) {
                  return (
                    <td key={j} data-label={headers[j]}>
                      <input
                        type="text"
                        value={cell}
                        onChange={(e) => updateRow(i, j, e.target.value, false, true)}
                        className="input-responsive"
                        placeholder="0"
                        inputMode="numeric"
                        pattern="[0-9,]*"
                      />
                    </td>
                  );
                }
                // For email columns, validate on blur
                if (isEmailColumn(headers[j])) {
                  return (
                    <td key={j} data-label={headers[j]}>
                      <input
                        type="email"
                        value={cell}
                        onChange={(e) =>
                          updateRow(
                            i,
                            j,
                            e.target.value.toUpperCase(),
                            false,
                            false,
                            true
                          )
                        }
                        onBlur={(e) => handleEmailBlur(i, j, e.target.value)}
                        className="input-responsive"
                        placeholder="EXAMPLE@EMAIL.COM"
                        style={
                          emailError && emailError.row === i && emailError.col === j
                            ? { borderColor: "red" }
                            : undefined
                        }
                      />
                    </td>
                  );
                }
                // Default: text input
                return (
                  <td key={j} data-label={headers[j]}>
                    <input
                      type="text"
                      value={cell}
                      onChange={(e) => updateRow(i, j, e.target.value, false)}
                      className="input-responsive"
                    />
                  </td>
                );
              })}
              {showAction && (
                <td data-label="Action">
                  <button
                    className="save-button"
                    style={{ backgroundColor: "#dc3545" }}
                    onClick={() => deleteRow(i)}
                    disabled={rows.length === 1}
                    title={rows.length === 1 ? "At least one row required" : "Delete row"}
                  >
                    Delete
                  </button>
                </td>
              )}
            </tr>
          ))}
        </tbody>
      </table>
      <div className="flex gap-[12px]">
        <button className="save-button" onClick={saveData}>Save</button>
        <button className="save-button" onClick={addRow} style={{ backgroundColor: '#28a745' }}>Add Row</button>
      </div>
      {/* Email validation popup */}
      {emailError && (
        <div
          style={{
            position: "fixed",
            top: 0,
            left: 0,
            width: "100vw",
            height: "100vh",
            background: "rgba(0,0,0,0.3)",
            zIndex: 1000,
            display: "flex",  
            alignItems: "center",
            justifyContent: "center"
          }}
          onClick={() => setEmailError(null)}
        >
          <div
            style={{
              background: "#fff",
              padding: "2rem",
              borderRadius: "8px",
              boxShadow: "0 2px 8px rgba(0,0,0,0.2)",
              minWidth: "300px",
              textAlign: "center"
            }}
            onClick={e => e.stopPropagation()}
          >
            <div style={{ color: "red", fontWeight: "bold", marginBottom: "1rem" }}>
              Invalid Email Address
            </div>
            <div>
              <span>
                <b>Value:</b> {emailError.value}
              </span>
            </div>
            <button
              className="save-button"
              style={{ marginTop: "1.5rem", backgroundColor: "#dc3545" }}
              onClick={() => setEmailError(null)}
            >
              Close
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
