import React, { useState, useEffect, useRef } from "react";
import { useAuth } from "../hooks/useAuth";
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";
import jsPDF from "jspdf";
import autoTable from "jspdf-autotable";
import { Navberbar } from "../components/pages/Navberbar";


// Helper: Format date as DD/MM/YYYY
const formatDateDDMMYYYY = (dateString: string) => {
  if (!dateString) return "-";
  const d = new Date(dateString);
  if (isNaN(d.getTime())) return "-";
  const day = String(d.getDate()).padStart(2, "0");
  const month = String(d.getMonth() + 1).padStart(2, "0");
  const year = d.getFullYear();
  return `${day}/${month}/${year}`;
};

// Helper: Format amount as 1,234.00
const formatAmount = (value: any) => {
  if (value === null || value === undefined || value === "") return "-";
  const num = Number(value);
  if (isNaN(num)) return value;
  return num.toLocaleString("en-IN", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

// Helper: Convert DD/MM/YYYY -> YYYY-MM-DD (ISO-like) if valid, else ""
const convertDDMMYYYYToISO = (value: string): string => {
  const match = /^(\d{2})\/(\d{2})\/(\d{4})$/.exec(value);
  if (!match) return "";
  const [, dd, mm, yyyy] = match;
  const day = Number(dd);
  const month = Number(mm);
  const year = Number(yyyy);
  const d = new Date(year, month - 1, day);
  if (
    d.getFullYear() !== year ||
    d.getMonth() !== month - 1 ||
    d.getDate() !== day
  ) {
    return "";
  }
  return `${yyyy}-${mm}-${dd}`;
};

// Helper: get timestamp (ms) from DD/MM/YYYY, returns NaN if invalid
const getTimestampFromDDMMYYYY = (value: string): number => {
  const iso = convertDDMMYYYYToISO(value);
  if (!iso) return NaN;
  return new Date(iso).getTime();
};

// Helper: mask user input to DD/MM/YYYY while typing
const maskToDDMMYYYY = (raw: string): string => {
  const digits = raw.replace(/\D/g, "").slice(0, 8);
  if (digits.length <= 2) return digits;
  if (digits.length <= 4) return `${digits.slice(0, 2)}/${digits.slice(2)}`;
  return `${digits.slice(0, 2)}/${digits.slice(2, 4)}/${digits.slice(4)}`;
};

// Helper: format Date object to DD/MM/YYYY
const formatDateToDDMMYYYY = (d: Date): string => {
  if (!d || isNaN(d.getTime())) return "";
  const day = String(d.getDate()).padStart(2, "0");
  const month = String(d.getMonth() + 1).padStart(2, "0");
  const year = d.getFullYear();
  return `${day}/${month}/${year}`;
};

type DateInputWithCalendarProps = {
  label: string;
  value: string;
  onChange: (v: string) => void;
};

const DateInputWithCalendar: React.FC<DateInputWithCalendarProps> = ({ label, value, onChange }) => {
  const [open, setOpen] = useState<boolean>(false);
  const containerRef = useRef<HTMLDivElement | null>(null);

  // Determine initial calendar month/year from value or today
  const today = new Date();
  const initialDate = value && convertDDMMYYYYToISO(value) ? new Date(convertDDMMYYYYToISO(value)) : today;
  const [viewMonth, setViewMonth] = useState<number>(initialDate.getMonth());
  const [viewYear, setViewYear] = useState<number>(initialDate.getFullYear());

  // Close on outside click
  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (!containerRef.current) return;
      if (!containerRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    };
    if (open) {
      document.addEventListener("mousedown", handler);
    }
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);

  // Update view when the value changes externally
  useEffect(() => {
    const iso = value ? convertDDMMYYYYToISO(value) : "";
    if (iso) {
      const d = new Date(iso);
      if (!isNaN(d.getTime())) {
        setViewMonth(d.getMonth());
        setViewYear(d.getFullYear());
      }
    }
  }, [value]);

  const monthNames = [
    "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
  ];
  const weekdays = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];

  const daysInMonth = (year: number, monthZeroBased: number) => new Date(year, monthZeroBased + 1, 0).getDate();
  const firstDayIndex = new Date(viewYear, viewMonth, 1).getDay();
  const numDays = daysInMonth(viewYear, viewMonth);

  const handleSelectDay = (day: number) => {
    const selected = new Date(viewYear, viewMonth, day);
    onChange(formatDateToDDMMYYYY(selected));
    setOpen(false);
  };

  const goPrevMonth = () => {
    const m = viewMonth - 1;
    if (m < 0) {
      setViewMonth(11);
      setViewYear(viewYear - 1);
    } else {
      setViewMonth(m);
    }
  };
  const goNextMonth = () => {
    const m = viewMonth + 1;
    if (m > 11) {
      setViewMonth(0);
      setViewYear(viewYear + 1);
    } else {
      setViewMonth(m);
    }
  };

  return (
    <div className="flex flex-col relative" ref={containerRef}>
      <span className="text-sm font-medium mb-1">{label}</span>
      <div className="flex items-center gap-2">
        <input
          type="text"
          inputMode="numeric"
          value={value}
          onChange={(e) => onChange(maskToDDMMYYYY(e.target.value))}
          className="px-3 py-2 border border-gray-300 rounded-md"
          placeholder="DD/MM/YYYY"
          maxLength={10}
        />
        <button
          type="button"
          onClick={() => setOpen((o) => !o)}
          className="px-2 py-2 border border-gray-300 rounded-md hover:bg-gray-100"
          aria-label="Open calendar"
        >
          📅
        </button>
      </div>
      {open && (
        <div className="absolute z-20 mt-2 bg-white border border-gray-200 rounded-md shadow p-3">
          <div className="flex items-center justify-between mb-2">
            <button type="button" onClick={goPrevMonth} className="px-2 py-1 hover:bg-gray-100 rounded">◀</button>
            <div className="font-medium">{monthNames[viewMonth]} {viewYear}</div>
            <button type="button" onClick={goNextMonth} className="px-2 py-1 hover:bg-gray-100 rounded">▶</button>
          </div>
          <div className="grid grid-cols-7 gap-1 text-xs text-gray-600 mb-1">
            {weekdays.map((w) => (
              <div key={w} className="text-center">{w}</div>
            ))}
          </div>
          <div className="grid grid-cols-7 gap-1">
            {Array.from({ length: firstDayIndex }).map((_, i) => (
              <div key={`blank-${i}`} />
            ))}
            {Array.from({ length: numDays }).map((_, i) => {
              const day = i + 1;
              const iso = value ? convertDDMMYYYYToISO(value) : "";
              const isSelected = iso && new Date(iso).getDate() === day && new Date(iso).getMonth() === viewMonth && new Date(iso).getFullYear() === viewYear;
              return (
                <button
                  key={day}
                  type="button"
                  onClick={() => handleSelectDay(day)}
                  className={`text-center px-2 py-1 rounded hover:bg-gray-100 ${isSelected ? 'bg-green-600 text-white hover:bg-green-600' : ''}`}
                >
                  {day}
                </button>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
};

const Report: React.FC = () => {
  const [activeTab, setActiveTab] = useState<string>("enquiry");
  const [data, setData] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [filter, setFilter] = useState<string>("");
  const [startDate, setStartDate] = useState<string>("");
  const [endDate, setEndDate] = useState<string>("");

  // Function to clear the filter
  const clearFilter = () => setFilter("");

  // Remove unnecessary console.log
  console.log(clearFilter);

  const { getProfile } = useAuth();
  const callFunction = getProfile();
  const profile_id = callFunction?.id;

  const tabs = [
    { key: "all", label: "ALL DATA REPORT" },
    { key: "enquiry", label: "ENQUIRY REPORT" },
    { key: "quote", label: "QUOTE REPORT" },
    { key: "confirmed", label: "CONFIRMED REPORT" },
    { key: "invoice", label: "INVOICE REPORT" },
    { key: "payment", label: "PAYMENT REPORT" },
    { key: "marketing", label: "MARKETING REPORT" },
  ];

  // Refetch data when activeTab, profile_id, startDate, or endDate changes
  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        let url = "";
        if (!profile_id) {
          setData([]);
          setLoading(false);
          return;
        }
        if (activeTab === "all") {
          url = `${import.meta.env.VITE_BACKEND_URL}api/pluton/get/market/profile/${profile_id}`;
        } else {
          switch (activeTab) {
            case "enquiry":
              url = `${import.meta.env.VITE_BACKEND_URL}api/pluton/get/enquiries/${profile_id}`;
              break;
            case "quote":
              url = `${import.meta.env.VITE_BACKEND_URL}api/pluton/get/quote/${profile_id}`;
              break;
            case "confirmed":
              url = `${import.meta.env.VITE_BACKEND_URL}api/pluton/get/confirm/${profile_id}`;
              break;
            case "invoice":
              url = `${import.meta.env.VITE_BACKEND_URL}api/pluton/get/invoices/${profile_id}`;
              break;
            case "payment":
              url = `${import.meta.env.VITE_BACKEND_URL}api/pluton/get/payment/${profile_id}`;
              break;
            case "marketing":
              url = `${import.meta.env.VITE_BACKEND_URL}api/pluton/get/marketing/${profile_id}`;
              break;
            default:
              url = "";
          }
        }

        // Add startDate and endDate as query params (convert DD/MM/YYYY -> YYYY-MM-DD)
        const params = [] as string[];
        const startISO = startDate ? convertDDMMYYYYToISO(startDate) : "";
        const endISO = endDate ? convertDDMMYYYYToISO(endDate) : "";
        if (startISO) params.push(`startDate=${encodeURIComponent(startISO)}`);
        if (endISO) params.push(`endDate=${encodeURIComponent(endISO)}`);
        const urlWithParams = params.length > 0 ? `${url}?${params.join("&")}` : url;

        if (!url) {
          setData([]);
          setLoading(false);
          return;
        }

        const res = await fetch(urlWithParams);
        if (!res.ok) throw new Error("Network response was not ok");
        const json = await res.json();

        if (activeTab === "all") {
          let combined: any[] = [];
          if (Array.isArray(json)) {
            json.forEach((entry: any) => {
              const { profiles_name, company_title, date } = entry;
              entry.enquiries?.forEach((item: any) =>
                combined.push({ type: "Enquiry", profiles_name, company_title, Date: item.created_at || date, ...item })
              );
              entry.quotes_submitted?.forEach((item: any) =>
                combined.push({ type: "Quote", profiles_name, company_title, Date: item.created_at || date, ...item })
              );
              entry.confirmed_work?.forEach((item: any) =>
                combined.push({ type: "Confirmed", profiles_name, company_title, Date: item.created_at || date, ...item })
              );
              entry.invoiced_work?.forEach((item: any) =>
                combined.push({ type: "Invoice", profiles_name, company_title, Date: item.created_at || date, ...item })
              );
              entry.payments_collected?.forEach((item: any) =>
                combined.push({ type: "Payment", profiles_name, company_title, Date: item.created_at || date, ...item })
              );
              entry.total_marketing?.forEach((item: any) =>
                combined.push({ type: "Marketing", profiles_name, company_title, Date: item.created_at || date, ...item })
              );
            });
          }
          setData(combined);
        } else {
          let values: any = [];
          if (Array.isArray(json)) {
            values = json;
          } else if (typeof json === "object" && json !== null) {
            const firstValue = Object.values(json)[0];
            values = Array.isArray(firstValue) ? firstValue : [];
          }
          // Rename created_at → Date
          values = values.map((v: any) => ({ ...v, Date: v.created_at }));
          setData(values);
        }
      } catch (err) {
        console.error("Error fetching data:", err);
        setData([]);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [activeTab, profile_id, startDate, endDate]);


  const filteredData = data.filter((row) => {
    const matchesText = JSON.stringify(row).toLowerCase().includes(filter.toLowerCase());
    const rowDate = new Date(row.Date || "").getTime();
    const start = startDate ? getTimestampFromDDMMYYYY(startDate) : NaN;
    const end = endDate ? getTimestampFromDDMMYYYY(endDate) : NaN;

    const matchesDate =
      (isNaN(start) || rowDate >= start) &&
      (isNaN(end) || rowDate <= end);

    return matchesText && matchesDate;
  });

  const allKeys = Array.from(
    new Set(data.flatMap((item) => Object.keys(item)).filter((key) => key !== "id" && key !== "created_at"))
  );


  const amountKeysByTab: Record<string, string[]> = {
    all: ["quote_amount", "so_amount", "invoice_amount", "rcvd_amount"],
    quote: ["quote_amount"],
    confirmed: ["so_amount"],
    invoice: ["invoice_amount"],
    payment: ["rcvd_amount"],
  };


  const exportToXLSX = () => {
    if (!filteredData.length) {
      alert("No data to export!");
      return;
    }


    const workbook = XLSX.utils.book_new();
    const worksheet = XLSX.utils.json_to_sheet([]);


    XLSX.utils.sheet_add_aoa(
      worksheet,
      [[`${tabs.find(t => t.key === activeTab)?.label}`]],
      { origin: "A1" }
    );


    const formattedStartDate = startDate || "All";
    const formattedEndDate = endDate || "All";
    XLSX.utils.sheet_add_aoa(
      worksheet,
      [[`Date Range: ${formattedStartDate} → ${formattedEndDate}`]],
      { origin: "A2" }
    );


    XLSX.utils.sheet_add_aoa(worksheet, [[]], { origin: "A3" });


    const headersBase = activeTab === "all"
      ? allKeys
      : getHeadersForTab(activeTab);
    const headers = headersBase.map((h) => String(h).toUpperCase());

    XLSX.utils.sheet_add_aoa(worksheet, [headers], { origin: "A4" });


    const dataToExport = activeTab === "all"
      ? filteredData.map((item) =>
          allKeys.map((key) => {
            if (key === "Date") return String(formatDateDDMMYYYY(item[key]) || "-").toUpperCase();
            if (amountKeysByTab.all.includes(key)) return String(formatAmount(item[key]) || "-").toUpperCase();
            const val = item[key] !== undefined && item[key] !== null && item[key] !== "" ? item[key] : "-";
            return String(val).toUpperCase();
          })
        )
      : filteredData.map((row) =>
          getRowDataForTab(activeTab, row).map((v) => String(v ?? "-").toUpperCase())
        );

    XLSX.utils.sheet_add_aoa(worksheet, dataToExport, { origin: "A5" });


    const range = XLSX.utils.decode_range(worksheet['!ref'] || "A1:A1");


    if (worksheet["A1"]) {
      worksheet["A1"].s = {
        font: { bold: true, sz: 16 },
        alignment: { horizontal: "center" }
      };
    }


    if (worksheet["A2"]) {
      worksheet["A2"].s = {
        alignment: { horizontal: "center" }
      };
    }


    for (let C = range.s.c; C <= range.e.c; ++C) {
      const cellAddress = XLSX.utils.encode_cell({ r: 3, c: C });
      if (worksheet[cellAddress]) {
        worksheet[cellAddress].s = {
          font: { bold: true },
          fill: { fgColor: { rgb: "E0E0E0" } }
        };
      }
    }

    worksheet['!merges'] = [
      { s: { r: 0, c: 0 }, e: { r: 0, c: headers.length - 1 } },
      { s: { r: 1, c: 0 }, e: { r: 1, c: headers.length - 1 } }
    ];

    XLSX.utils.book_append_sheet(workbook, worksheet, `${activeTab}_Report`);

    const excelBuffer = XLSX.write(workbook, { bookType: "xlsx", type: "array" });
    const dataBlob = new Blob([excelBuffer], { type: "application/octet-stream" });
    saveAs(dataBlob, `${activeTab}_Report.xlsx`);
  };

  const exportToPDF = () => {
    if (!filteredData.length) {
      alert("No data to export!");
      return;
    }

    const headersBase = activeTab === "all"
      ? allKeys
      : getHeadersForTab(activeTab);
    const headers = headersBase.map((h) => String(h).toUpperCase());

    const rows = activeTab === "all"
      ? filteredData.map((item) =>
          allKeys.map((key) => {
            if (key === "Date") return String(formatDateDDMMYYYY(item[key]) || "-").toUpperCase();
            if (amountKeysByTab.all.includes(key)) return String(formatAmount(item[key]) || "-").toUpperCase();
            const val = item[key] !== undefined && item[key] !== null && item[key] !== "" ? item[key] : "-";
            return String(val).toUpperCase();
          })
        )
      : filteredData.map((row) =>
          getRowDataForTab(activeTab, row).map((v) => String(v ?? "-").toUpperCase())
        );

    const isWide = headers.length >= 6;
    const doc = new jsPDF({ orientation: isWide ? "landscape" : "portrait" });

    const title = `${tabs.find(t => t.key === activeTab)?.label}`;
    const formattedStartDate = (startDate || "All").toUpperCase();
    const formattedEndDate = (endDate || "All").toUpperCase();
    const dateRange = `DATE RANGE: ${formattedStartDate} → ${formattedEndDate}`;

    doc.setFontSize(14);
    doc.text(String(title).toUpperCase(), 14, 14);
    doc.setFontSize(10);
    doc.text(String(dateRange).toUpperCase(), 14, 20);

    autoTable(doc, {
      head: [headers],
      body: rows as unknown as any[],
      startY: 26,
      theme: "grid",
      styles: {
        fontSize: 7,
        halign: "left",
        valign: "top",
        cellPadding: 2,
        overflow: "linebreak",
      },
      headStyles: { fillColor: [224, 224, 224], halign: "left" },
      margin: { left: 10, right: 10 },
      tableWidth: "wrap",
      columnStyles: Object.fromEntries(headers.map((_, i) => [i, { cellWidth: "wrap" }]))
    });

    doc.save(`${activeTab}_Report.pdf`);
  };

  // Helper functions for export
  const getHeadersForTab = (tab: string) => {
    switch (tab) {
      case "enquiry":
        return ["DATE", "CUSTOMER NAME", "TYPE OF WORK", "DESCRIPTIONS"];
      case "quote":
        return ["DATE", "CUSTOMER NAME", "TYPE OF WORK", "QUOTE NO", "AMOUNT", "REMARKS"];
      case "confirmed":
        return ["DATE", "CUSTOMER NAME", "TYPE OF WORK", "SO NO", "SO AMOUNT", "REMARKS"];
      case "invoice":
        return ["DATE", "CUSTOMER NAME", "TYPE OF WORK", "INVOICE NO", "INVOICE AMOUNT", "REMARKS"];
      case "payment":
        return ["DATE", "CUSTOMER NAME", "INVOICE NO", "RECEIVED AMOUNT", "REMARKS"];
      case "marketing":
        return ["DATE", "CLIENT NAME", "EMAIL", "CONTACT NO", "STATUS"];
      default:
        return allKeys.map((k) => String(k).toUpperCase());
    }
  };

  const getRowDataForTab = (tab: string, row: any) => {
    switch (tab) {
      case "enquiry":
        return [
          formatDateDDMMYYYY(row.Date),
          row.customer_name || "-",
          row.type_of_work || "-",
          row.descriptions || "-"
        ];
      case "quote":
        return [
          formatDateDDMMYYYY(row.Date),
          row.customer_name || "-",
          row.type_of_work || "-",
          row.Quote_no || "-",
          formatAmount(row.quote_amount),
          row.remarks || "-"
        ];
      case "confirmed":
        return [
          formatDateDDMMYYYY(row.Date),
          row.customer_name || "-",
          row.type_of_work || "-",
          row.so_no || "-",
          formatAmount(row.so_amount),
          row.remarks || "-"
        ];
      case "invoice":
        return [
          formatDateDDMMYYYY(row.Date),
          row.customer_name || "-",
          row.type_of_work || "-",
          row.invoice_no || "-",
          formatAmount(row.invoice_amount),
          row.remarks || "-"
        ];
      case "payment":
        return [
          formatDateDDMMYYYY(row.Date),
          row.customer_name || "-",
          row.invoice_no || "-",
          formatAmount(row.rcvd_amount),
          row.remarks || "-"
        ];
      case "marketing":
        return [
          formatDateDDMMYYYY(row.Date),
          row.client_name || "-",
          row.email || "-",
          row.contact_no || "-",
          row.status || "-"
        ];
      default:
        return [];
    }
  };


  const renderHeaders = () => {
    switch (activeTab) {
      case "enquiry":
        return (
          <tr className="bg-gray-100">
            <th className="px-4 py-3 text-left font-semibold">DATE</th>
            <th className="px-4 py-3 text-left font-semibold">CUSTOMER NAME</th>
            <th className="px-4 py-3 text-left font-semibold">TYPE OF WORK</th>
            <th className="px-4 py-3 text-left font-semibold">DESCRIPTIONS</th>
          </tr>
        );
      case "quote":
        return (
          <tr className="bg-gray-100">
            <th className="px-4 py-3 text-left font-semibold">DATE</th>
            <th className="px-4 py-3 text-left font-semibold">CUSTOMER NAME</th>
            <th className="px-4 py-3 text-left font-semibold">TYPE OF WORK</th>
            <th className="px-4 py-3 text-left font-semibold">QUOTE NO</th>
            <th className="px-4 py-3 text-left font-semibold">AMOUNT</th>
            <th className="px-4 py-3 text-left font-semibold">REMARKS</th>
          </tr>
        );
      case "confirmed":
        return (
          <tr className="bg-gray-100">
            <th className="px-4 py-3 text-left font-semibold">DATE</th>
            <th className="px-4 py-3 text-left font-semibold">CUSTOMER NAME</th>
            <th className="px-4 py-3 text-left font-semibold">TYPE OF WORK</th>
            <th className="px-4 py-3 text-left font-semibold">SO NO</th>
            <th className="px-4 py-3 text-left font-semibold">SO AMOUNT</th>
            <th className="px-4 py-3 text-left font-semibold">REMARKS</th>
          </tr>
        );
      case "invoice":
        return (
          <tr className="bg-gray-100">
            <th className="px-4 py-3 text-left font-semibold">DATE</th>
            <th className="px-4 py-3 text-left font-semibold">CUSTOMER NAME</th>
            <th className="px-4 py-3 text-left font-semibold">TYPE OF WORK</th>
            <th className="px-4 py-3 text-left font-semibold">INVOICE NO</th>
            <th className="px-4 py-3 text-left font-semibold">INVOICE AMOUNT</th>
            <th className="px-4 py-3 text-left font-semibold">REMARKS</th>
          </tr>
        );
      case "payment":
        return (
          <tr className="bg-gray-100">
            <th className="px-4 py-3 text-left font-semibold">DATE</th>
            <th className="px-4 py-3 text-left font-semibold">CUSTOMER NAME</th>
            <th className="px-4 py-3 text-left font-semibold">INVOICE NO</th>
            <th className="px-4 py-3 text-left font-semibold">RECEIVED AMOUNT</th>
            <th className="px-4 py-3 text-left font-semibold">REMARKS</th>
          </tr>
        );
      case "marketing":
        return (
          <tr className="bg-gray-100">
            <th className="px-4 py-3 text-left font-semibold">DATE</th>
            <th className="px-4 py-3 text-left font-semibold">CLIENT NAME</th>
            <th className="px-4 py-3 text-left font-semibold">EMAIL</th>
            <th className="px-4 py-3 text-left font-semibold">CONTACT NO</th>
            <th className="px-4 py-3 text-left font-semibold">STATUS</th>
          </tr>
        );
      default:
        return (
          <tr className="bg-gray-100">
            {allKeys.map((key) => (
              <th key={key} className="px-4 py-3 text-left font-semibold uppercase">{key.toUpperCase()}</th>
            ))}
          </tr>
        );
    }
  };

  // ✅ Rows
  const renderRows = () => {
    if (activeTab === "all") {
      const dateKey = "Date";
      const otherKeys = allKeys.filter((key) => key !== dateKey);
      return filteredData.map((item, rowIndex) => (
        <tr key={rowIndex} className="border-b hover:bg-gray-50">
          <td className="px-4 py-3">{String(formatDateDDMMYYYY(item[dateKey]) || "-").toUpperCase()}</td>
          {otherKeys.map((key) => {
            if (amountKeysByTab.all.includes(key)) {
              return (
                <td key={key} className="px-4 py-3">
                  {String(formatAmount(item[key]) || "-").toUpperCase()}
                </td>
              );
            }
            const val = item[key] !== undefined && item[key] !== null && item[key] !== "" ? item[key] : "-";
            return (
              <td key={key} className="px-4 py-3">
                {String(val).toUpperCase()}
              </td>
            );
          })}
        </tr>
      ));
    }

    return filteredData.map((row: any, idx: number) => (
      <tr key={row.id ?? idx} className="border-b hover:bg-gray-50">
        {activeTab === "enquiry" && (
          <>
            <td className="px-4 py-3">{formatDateDDMMYYYY(row.Date)}</td>
            <td className="px-4 py-3">{row.customer_name || "-"}</td>
            <td className="px-4 py-3">{row.type_of_work || "-"}</td>
            <td className="px-4 py-3">{row.descriptions || "-"}</td>
          </>
        )}
        {activeTab === "quote" && (
          <>
            <td className="px-4 py-3">{formatDateDDMMYYYY(row.Date)}</td>
            <td className="px-4 py-3">{row.customer_name || "-"}</td>
            <td className="px-4 py-3">{row.type_of_work || "-"}</td>
            <td className="px-4 py-3">{row.Quote_no || "-"}</td>
            <td className="px-4 py-3" style={{ textAlign: "right" }}>{formatAmount(row.quote_amount)}</td>
            <td className="px-4 py-3">{row.remarks || "-"}</td>
          </>
        )}
        {activeTab === "confirmed" && (
          <>
            <td className="px-4 py-3">{formatDateDDMMYYYY(row.Date)}</td>
            <td className="px-4 py-3">{row.customer_name || "-"}</td>
            <td className="px-4 py-3">{row.type_of_work || "-"}</td>
            <td className="px-4 py-3">{row.so_no || "-"}</td>
            <td className="px-4 py-3" style={{ textAlign: "right" }}>{formatAmount(row.so_amount)}</td>
            <td className="px-4 py-3">{row.remarks || "-"}</td>
          </>
        )}
        {activeTab === "invoice" && (
          <>
            <td className="px-4 py-3">{formatDateDDMMYYYY(row.Date)}</td>
            <td className="px-4 py-3">{row.customer_name || "-"}</td>
            <td className="px-4 py-3">{row.type_of_work || "-"}</td>
            <td className="px-4 py-3">{row.invoice_no || "-"}</td>
            <td className="px-4 py-3" style={{ textAlign: "right" }}>{formatAmount(row.invoice_amount)}</td>
            <td className="px-4 py-3">{row.remarks || "-"}</td>
          </>
        )}
        {activeTab === "payment" && (
          <>
            <td className="px-4 py-3">{formatDateDDMMYYYY(row.Date)}</td>
            <td className="px-4 py-3">{row.customer_name || "-"}</td>
            <td className="px-4 py-3">{row.invoice_no || "-"}</td>
            <td className="px-4 py-3" style={{ textAlign: "right" }}>{formatAmount(row.rcvd_amount)}</td>
            <td className="px-4 py-3">{row.remarks || "-"}</td>
          </>
        )}
        {activeTab === "marketing" && (
          <>
            <td className="px-4 py-3">{formatDateDDMMYYYY(row.Date)}</td>
            <td className="px-4 py-3">{row.client_name || "-"}</td>
            <td className="px-4 py-3">{row.email || "-"}</td>
            <td className="px-4 py-3">{row.contact_no || "-"}</td>
            <td className="px-4 py-3">{row.status || "-"}</td>
          </>
        )}
      </tr>
    ));
  };

  const scrollRef = useRef<HTMLDivElement | null>(null);

  const ExportMenu: React.FC<{ buttonClassName?: string }> = ({ buttonClassName }) => {
    const [open, setOpen] = useState(false);
    const menuRef = useRef<HTMLDivElement | null>(null);

    useEffect(() => {
      const onDocClick = (e: MouseEvent) => {
        if (!menuRef.current) return;
        if (!menuRef.current.contains(e.target as Node)) setOpen(false);
      };
      document.addEventListener("mousedown", onDocClick);
      return () => document.removeEventListener("mousedown", onDocClick);
    }, []);

    const handleChoice = (type: "pdf" | "xlsx") => {
      setOpen(false);
      if (type === "pdf") exportToPDF();
      if (type === "xlsx") exportToXLSX();
    };

    return (
      <div className="relative" ref={menuRef}>
        <button
          onClick={() => setOpen(o => !o)}
          className={`mt-2 md:mt-0 px-3 py-2 bg-green-600 text-white rounded-md shadow hover:bg-green-700 transition-colors flex items-center gap-2 ${buttonClassName || ""}`}
        >
          <span className="text-lg">⬇</span>
          EXPORT
        </button>
        {open && (
          <div className="absolute right-0 mt-2 w-56 bg-white border border-gray-200 rounded-md shadow-lg z-30">
            <div className="px-3 py-1 text-xs text-gray-500">EXPORT AS</div>

            <button
              onClick={() => handleChoice("pdf")}
              className="w-full flex items-center gap-2 px-3 py-2 hover:bg-gray-100 text-left"
            >
              <span className="text-lg">📄</span>
              <div className="font-medium">PDF</div>
            </button>

            <button
              onClick={() => handleChoice("xlsx")}
              className="w-full flex items-center gap-2 px-3 py-2 hover:bg-gray-100 text-left"
            >
              <span className="text-lg">📊</span>
              <div>
                <div className="font-medium">XLSX</div>
                <div className="text-xs text-gray-500">MICROSOFT EXCEL</div>
              </div>
            </button>
          </div>
        )}
      </div>

    );
  };

  return (
    <div className="p-4 md:p-6 max-w-full bg-gray-50 min-h-screen">
      <Navberbar />
      {/* Title */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between mb-6">
        <h1 className="text-2xl font-bold text-gray-800">📊 REPORTS</h1>
      </div>



      {/* Tabs */}
      <div className="flex flex-wrap gap-2 mb-6 bg-white p-3 rounded-lg shadow-sm">
        {tabs.map((tab) => (
          <button
            key={tab.key}
            onClick={() => {
              setActiveTab(tab.key);
              setStartDate("");
              setEndDate("");
            }}
            className={`px-4 py-2 rounded-md font-medium transition-all ${activeTab === tab.key
              ? "bg-green-600 text-white shadow-md"
              : "bg-white text-black-700 hover:bg-gray-100 border border-gray-200"
              }`}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {/* Filters */}
      <div className="flex gap-5 mb-6 flex-wrap bg-white p-4 rounded-lg shadow-sm">
        <DateInputWithCalendar label="START DATE" value={startDate} onChange={setStartDate} />
        <DateInputWithCalendar label="END DATE" value={endDate} onChange={setEndDate} />
        <div className="flex-1 flex justify-end">
          <ExportMenu />
        </div>
      </div>

      {
        loading ? (
          <div className="flex justify-center items-center h-64">
            <p className="text-center text-gray-500">Loading...</p>
          </div>
        ) : (
          <div ref={scrollRef} className="overflow-x-auto bg-white rounded-lg shadow">
            <table className="min-w-full">
              <thead>{renderHeaders()}</thead>
              <tbody>{renderRows()}</tbody>
            </table>
            {filteredData.length === 0 && (
              <div className="p-8 text-center text-gray-500">
                No data found for the selected criteria
              </div>
            )}
          </div>
        )
      }
    </div >
  );
};

export default Report;
