import { useRouter } from 'next/router';
import { useEffect, useState, useRef  } from 'react';
import { toast } from 'react-hot-toast';
import {
  EllipsisVerticalIcon,
  MagnifyingGlassIcon,
  ChevronDownIcon,
  ChevronUpIcon,
} from '@heroicons/react/24/outline';
import useAuth from '@/core/hooks/useAuth';
import {
  downloadPurchaseOrder,
  downloadQuotation,
} from '../utils/transactions';
import useTransactions from '../hooks/useTransactions';
import currencyFormat from '@/core/utils/currencyFormat';
import cancelTransactionApi from '../api/cancelTransactionApi';
import TransactionStatusBadge from './TransactionStatusBadge';
import Spinner from '@/core/components/elements/Spinner/Spinner';
import Link from '@/core/components/elements/Link/Link';
import BottomPopup from '@/core/components/elements/Popup/BottomPopup';
import Pagination from '@/core/components/elements/Pagination/Pagination';
import { toQuery } from 'lodash-contrib';
import _ from 'lodash';
import Alert from '@/core/components/elements/Alert/Alert';
import MobileView from '@/core/components/views/MobileView';
import DesktopView from '@/core/components/views/DesktopView';
import Menu from '@/lib/auth/components/Menu';
import * as XLSX from 'xlsx';
import getSite from '../api/listSiteApi';
import transactionsApi from '../api/transactionsApi';
import { motion } from 'framer-motion';
import Image from '@/core/components/elements/Image/Image';
import { upsertUserCart } from '~/services/cart';
import { useProductCartContext } from '@/contexts/ProductCartContext';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Navigation } from 'swiper';
import 'swiper/css';
import 'swiper/css/navigation';
import { Calendar } from 'lucide-react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import { DateRangePicker } from 'react-date-range';
import { addDays } from 'date-fns';
import 'react-date-range/dist/styles.css'; // main style file
import 'react-date-range/dist/theme/default.css'; // theme css file
import { Popover } from '@headlessui/react';
const Transactions = ({ context = '' }) => {
  const auth = useAuth();
  const router = useRouter();
  const swiperRef = useRef(null);
  const {
    q = '',
    page = 1,
    site = null,
    limit = 15,
    status = 'all',
    sort = 'none',
    startDate = null,
    endDate = new Date(),
  } = router.query;
  const {
    productCart,
    setRefreshCart,
    setProductCart,
    refreshCart,
    isLoading,
    setIsloading,
  } = useProductCartContext();
  const [inputQuery, setInputQuery] = useState(q);
  const [toOthers, setToOthers] = useState(null);
  const [toCancel, setToCancel] = useState(null);
  const [listSites, setListSites] = useState([]);
  const [isOpen, setIsOpen] = useState(false);
  const [siteFilter, setSiteFilter] = useState(site);
  const [pageNew, setPageNew] = useState(page);
  const [limitNew, setLimitNew] = useState(limit);
  // const [status, setStatus] = useState('idle');
  const [statusNew, setStatusNew] = useState(status);
  const [sortNew, setSortNew] = useState(sort);
  const [contextNew, setcontextNew] = useState(router.query.context || context);
  const [dateRange, setDateRange] = useState([null, null]);
  // const [startDate, endDate] = dateRange;
  const [isOpenCalender, setIsOpenCalender] = useState(false);
  const [cachedAllData, setCachedAllData] = useState(null); // Simpan data "All"
  const [currentData, setCurrentData] = useState([]);     // Data yang ditampilkan
  const calendarRef = useRef(null);
  const [isDateSelected, setIsDateSelected] = useState(false);

  const parseDate = (date) => {
    if (!date || date === 'null') return null;
    if (date instanceof Date) return date;
    const [day, month, year] = date.split('/').map(Number);
    return new Date(year, month - 1, day);
  };

  const [state, setState] = useState([
    {
      startDate: startDate != null || 'null' ? parseDate(startDate) : null, // Gunakan `parseDate`
      endDate: startDate == null ? endDate : parseDate(endDate),
      key: 'selection',
    },
  ]);

  const query = {
    name: q,
    offset: (pageNew - 1) * limitNew,
    context: contextNew,
    limit: limitNew,
    status: statusNew,
    sort: sortNew,
    startDate: state[0].startDate
      ? state[0].startDate.toLocaleDateString('id-ID')
      : null,
    endDate: state[0]?.endDate?.toLocaleDateString('id-ID'),
    site:
      siteFilter || (auth?.webRole === null && auth?.site ? auth.site : null),
  };
  const statuses = [
    { id: 'all', label: 'Semua' },
    { id: 'quotation', label: 'Pending Quotation' },
    { id: 'diproses', label: 'Pesanan Diproses' },
    { id: 'dikemas', label: 'Pesanan Dikemas' },
    { id: 'partial', label: 'Dikirim Sebagian' },
    { id: 'dikirim', label: 'Pesanan Dikirim' },
    { id: 'selesai', label: 'Pesanan Selesai' },
    { id: 'cancel', label: 'Pesanan Dibatalkan' },
  ];

  const contextLabelMap = {
    draft: 'Pending Quotation',
    waiting: 'Pesanan Diproses',
    sale: 'Pesanan Dikemas',
    partial_shipping: 'Dikirim Sebagian',
    shipping: 'Pesanan Dikirim',
    done: 'Pesanan Selesai',
    cancel: 'Pesanan Dibatalkan',
  };

  const sortes = [
    { id: 'none', label: 'Urutkan' },
    { id: 'asc', label: 'dari yang terkecil' },
    { id: 'desc', label: 'dari yang terbesar' },
  ];
  const { transactions } = useTransactions({ query });
  const fetchSite = async () => {
    const site = await getSite();
    setListSites(site.sites);
  };

  const submitCancelTransaction = async () => {
    const isCancelled = await cancelTransactionApi({
      transaction: toCancel,
    });
    if (isCancelled) {
      toast.success('Berhasil batalkan transaksi');
      transactions.refetch();
    }
    setToCancel(null);
  };

  const pageCount = Math.ceil(transactions?.data?.saleOrderTotal / limitNew);
  let pageQuery = _.omit(query, ['limit', 'offset', 'context']);
  pageQuery = _.pickBy(
    pageQuery,
    (value, key) => value !== '' && !(key === 'page' && value === '1')
  );
  pageQuery = toQuery(pageQuery);

  const handleSubmit = (e) => {
    e.preventDefault();
    const queryParams = {};
    if (inputQuery) queryParams.q = inputQuery;
    if (siteFilter) queryParams.site = siteFilter;
    router.push({
      pathname: router.pathname,
      query: queryParams,
    });
  };

  const handleSiteFilterChange = (e) => {
    setSiteFilter(e.target.value);
    const queryParams = {};
    if (inputQuery) queryParams.q = inputQuery;
    if (e.target.value) queryParams.site = e.target.value;
    router.push({
      pathname: router.pathname,
      query: queryParams,
    });
  };

  const exportToExcel = (data, siteFilter) => {
    const fieldsToExport = [
      'No. Transaksi',
      'No. PO',
      'Tanggal',
      'Created By',
      'Salesperson',
      'Total',
      'Status',
    ];
    const rowsToExport = [];

    data.forEach((saleOrder) => {
      const row = {
        'No. Transaksi': saleOrder.name,
        'No. PO': saleOrder.purchaseOrderName || '-',
        Tanggal: saleOrder.dateOrder || '-',
        'Created By': saleOrder.address.customer?.name || '-',
        Salesperson: saleOrder.sales,
        Total: currencyFormat(saleOrder.amountTotal),
        Status: contextLabelMap[saleOrder.status] || saleOrder.status,
      };
      if (siteFilter) {
        row['Site'] = siteFilter;
      }
      rowsToExport.push(row);
    });

    const worksheet = XLSX.utils.json_to_sheet(rowsToExport, {
      header: fieldsToExport,
    });

    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    XLSX.writeFile(workbook, 'transactions.xlsx');
  };

  const handleExportCSV = async () => {
    const dataToExport = await getAllData();

    exportToCSV(dataToExport?.saleOrders, siteFilter);
  };

  const exportToCSV = (data, siteFilter) => {
    const fieldsToExport = [
      'No. Transaksi',
      'No. PO',
      'Tanggal',
      'Created By',
      'Salesperson',
      'Total',
      'Status',
    ];

    if (siteFilter) {
      fieldsToExport.push('Site');
    }

    const rowsToExport = data.map((saleOrder) => {
      const row = [
        saleOrder.name,
        saleOrder.purchaseOrderName || '-',
        saleOrder.dateOrder || '-',
        saleOrder.address.customer?.name || '-',
        saleOrder.sales,
        currencyFormat(saleOrder.amountTotal),
        contextLabelMap[saleOrder.status] || saleOrder.status,
      ];

      if (siteFilter) {
        row.push(siteFilter);
      }

      return row.join(',');
    });

    const csvContent =
      'data:text/csv;charset=utf-8,' +
      [fieldsToExport.join(','), ...rowsToExport].join('\n');

    const encodedUri = encodeURI(csvContent);
    const link = document.createElement('a');
    link.setAttribute('href', encodedUri);
    link.setAttribute('download', 'transactions.csv');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const getAllData = async () => {
    const query = {
      name: q,
      offset: (pageNew - 1) * limitNew,
      limit: limitNew,
      context: contextNew[statusNew] || 'all',
      sort: sortNew,
      startDate: state[0]?.startDate
        ? state[0].startDate.toLocaleDateString('id-ID')
        : null,
      endDate: state[0]?.endDate
        ? state[0].endDate.toLocaleDateString('id-ID')
        : null,
      site:
        siteFilter || (auth?.webRole === null && auth?.site ? auth.site : null),
    };
    const queryString = toQuery(query);
    const data = await transactionsApi({ query: queryString });
    return data;
  };

  const handleExportExcel = async () => {
    const dataToExport = await getAllData();

    exportToExcel(dataToExport?.saleOrders, siteFilter);
  };

  const handleDownload = (format) => {
    handleExport(format);
    setIsOpen(false);
  };

  const handleExport = (format) => {
    if (format === 'csv') {
      handleExportCSV();
    } else if (format === 'xlsx') {
      handleExportExcel();
    }
  };

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (
        calendarRef.current &&
        !calendarRef.current.contains(event.target)
      ) {
        setIsOpenCalender(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  const startItem = 1 + (pageNew - 1) * limitNew;
  const endItem = Math.min(
    limitNew * pageNew,
    transactions?.data?.saleOrderTotal
  );

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

  const handleBuyBack = async (products) => {
    try {
      // setStatus('loading');
      console.log("Products to add:", products);

      const results = await Promise.all(
        products.map((product) =>
          upsertUserCart({
            userId: auth.id,
            type: 'product',
            id: product.id,
            qty: product.quantity,
            selected: true,
            source: 'add_to_cart',
            qtyAppend: true,
          }).catch(error => {
            return { error, product };
          })
        )
      );

      const failedOperations = results.filter(result => result && result.error);
      // console.log(results);
      
      if (failedOperations.length > 0) {
        console.error('Some products failed to add to cart:', failedOperations);
        toast.error(`${failedOperations.length} produk gagal ditambahkan ke keranjang`);
        
        // You might want to proceed with the successful ones or handle differently
        if (failedOperations.length < products.length) {
          toast.success(`${products.length - failedOperations.length} produk berhasil ditambahkan ke keranjang`);
          setRefreshCart(true);
          router.push('/shop/cart');
        }
        return;
      }

      // All operations succeeded
      setRefreshCart(true);
      toast.success('Semua produk berhasil ditambahkan ke keranjang belanja');
      router.push('/shop/cart');

    } catch (error) {
      console.error('Gagal menambahkan produk ke keranjang:', error);
      toast.error('Terjadi kesalahan saat menambahkan produk ke keranjang');
      // setStatus('error');
    }
  };

  
  const handleStatusChange = async (status) => {
    setStatusNew(status);
    setPageNew(1);

    if (status === 'all' && cachedAllData) {
      setCurrentData(cachedAllData); 
      return; 
    }
    const data = await fetchSite(status, 1);
    
    if (status === 'all') {
      setCachedAllData(data);
    }

    setCurrentData(data);
  };

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


  const handleReset = () => {
    setState([
      {
        startDate: null,
        endDate: new Date(),
        key: 'selection',
      },
    ]);
    setIsOpenCalender(false);
    router.push(`${router.pathname}`);
  };

  const formatDate = (dateString) => {
    const months = [
      'Januari',
      'Februari',
      'Maret',
      'April',
      'Mei',
      'Juni',
      'Juli',
      'Agustus',
      'September',
      'Oktober',
      'November',
      'Desember',
    ];

    const [day, month, year] = dateString.split('/');
    return `${day} ${months[parseInt(month, 10) - 1]} ${year}`;
  };

  return (
    <>
      <MobileView>
        <div className=' flex flex-col gap-y-4'>
          <div className='grid grid-cols-[40%_40%_15%] justify-between items-center gap-2 w-full '>
            <select
              value={statusNew}
              onChange={(e) => handleStatusChange(e.target.value)}
              className='border border-gray-300 rounded-lg px-2 py-2 text-xs bg-white shadow-sm focus:outline-none focus:ring-2 focus:ring-red-500'
            >
              {statuses.map((status) => (
                <option key={status.id} value={status.id}>
                  {status.label}
                </option>
              ))}
            </select>
            <select
              value={sortNew}
              onChange={(e) => setSortNew(e.target.value)}
              className='border border-gray-300 rounded-lg px-2 py-2 text-xs bg-white shadow-sm focus:outline-none focus:ring-2 focus:ring-red-500'
            >
              {sortes.map((status) => (
                <option key={status.id} value={status.id}>
                  {status.label}
                </option>
              ))}
            </select>
            <div ref={calendarRef} className='relative inline-block'>
              <button
                type='button'
                className='p-1 w-full h-auto cursor-pointer border hover:bg-gray-100 rounded transition duration-150 ease-in-out flex items-center justify-center'
                onClick={() => setIsOpenCalender((prev) => !prev)}
              >
                <span className='text-nowrap px-1 truncate flex items-center gap-1'>
                  {state[0]?.startDate ? (
                    `${state[0].startDate.toLocaleDateString()} - ${state[0].endDate.toLocaleDateString()}`
                  ) : (
                    <Calendar size={20} className='text-gray-500' />
                  )}
                </span>
              </button>
              {isOpenCalender && (
                <div className='absolute right-1 mt-2 bg-white p-4 rounded shadow-lg z-50'>
                  {/* Tombol silang di sudut kanan atas */}
                  <button
                    onClick={() => setIsOpenCalender(false)}
                    className='absolute top-2 right-2 text-gray-600 hover:text-black text-xl font-bold'
                  >
                    &times;
                  </button>
                  <DateRangePicker
                    onChange={(item) => setState([item.selection])}
                    showSelectionPreview={false}
                    maxDate={new Date()}
                    moveRangeOnFirstSelection={false}
                    months={1}
                    ranges={state}
                    className='w-full'
                  />
                  <style>{`
                    /* Atur container agar menjadi column */
                    .rdrCalendarWrapper {
                      display: flex;
                      flex-direction: column;
                    }
                    .rdrDateRangePickerWrapper  {
                      display: flex;
                      flex-direction: column;
                    }

                    /* Pindahkan rdrStaticRanges ke atas */
                    .rdrDefinedRangesWrapper {
                      order: -1;
                      width: fit-content;
                    }
                    .rdrStaticRanges {
                      flex-direction: row;
                      margin-right: 2px;
                    }

                    /* Sembunyikan bagian input manual */
                    .rdrInputRanges {
                      display: none !important;
                    }

                    .rdrStaticRangeLabel {
                      padding: 10px 10px;
                    }
                    .rdrMonth {
                      width: -moz-available;
                    }
                  `}</style>
                  <div className='flex flex-row justify-end gap-3 mt-2'>
                    <button
                      className='px-4 py-1 bg-red-500 text-white rounded'
                      onClick={handleReset}
                    >
                      Reset
                    </button>
                  </div>
                </div>
              )}
            </div>
            {/* <div className='border border-gray-300 rounded-lg px-1 py-1 bg-white shadow-sm focus:outline-none focus:ring-2 focus:ring-red-500 text-xs'>
              <DatePicker
                closeOnScroll={(e) => e.target === document}
                selectsRange={true}
                startDate={startDate}
                endDate={endDate}
                dateFormat='dd/MM'
                className='w-full'
                maxDate={new Date()}
                placeholderText='Semua Tanggal'
                onChange={(update) => {
                  setDateRange(update);
                }}
                withPortal
                isClearable={true}
              />
            </div> */}
          </div>
          <div className='flex flex-row justify-between items-center gap-2'>
            <form className='flex' onSubmit={handleSubmit}>
              <button
                className='btn-light border-r-0 rounded-r-none bg-transparent px-3'
                type='submit'
              >
                <MagnifyingGlassIcon className='w-6' />
              </button>
              <input
                type='text'
                className='form-input border-l-0 rounded-l-none text-xs'
                placeholder='Cari Transaksi...'
                value={inputQuery}
                onChange={(e) => setInputQuery(e.target.value)}
              />
            </form>
            <div className='flex flex-row gap-2 items-center justify-center text-nowrap'>
              <p className='text-xs'>
                Menampilkan {startItem}-
                {endItem
                  ? endItem
                  : transactions?.data?.saleOrderTotal
                  ? transactions?.data?.saleOrderTotal
                  : limitNew * pageNew}{' '}
                dari{' '}
                {transactions?.data?.saleOrderTotal
                  ? transactions?.data?.saleOrderTotal
                  : limitNew * pageNew}
              </p>
              <select
                id='limitSelect'
                value={limitNew}
                onChange={(e) => {
                  setLimitNew(Number(e.target.value));
                  setPageNew(1);
                }}
                className='border p-2 text-xs'
              >
                <option value={10}>10</option>
                <option value={15}>15</option>
                <option value={20}>20</option>
              </select>
            </div>
          </div>

          {transactions.isLoading && (
            <div className='flex justify-center my-4'>
              <Spinner className='w-6 text-gray_r-12/50 fill-gray_r-12' />
            </div>
          )}

          {!transactions.isLoading &&
            transactions.data?.saleOrders?.length === 0 && (
              <Alert type='info' className='text-center'>
                Tidak ada transaksi
              </Alert>
            )}

          {transactions.data?.saleOrders?.map((saleOrder, index) => (
            <div
              className='p-4 shadow border border-gray_r-3 text-xs rounded-md flex flex-col gap-2'
              key={index}
            >
              <div className='flex flex-row justify-between items-start'>
                <Link href={`${router.pathname}/${saleOrder.id}`}>
                  <h2 className='text-danger-500 text-base'>
                    {saleOrder.name}
                  </h2>
                  <span className='font-medium text-black opacity-75'>
                    {formatDate(saleOrder.dateOrder.split(' ')[0]) || '-'}
                  </span>
                </Link>
                <div className='flex gap-x-1 justify-end'>
                  <TransactionStatusBadge status={saleOrder.status} />
                  <EllipsisVerticalIcon
                    className='w-5 h-5'
                    onClick={() => setToOthers(saleOrder)}
                  />
                </div>
              </div>
              <div className='col-span-2 h-[1px] w-full bg-gray-300'></div>
              <Link
                href={`${router.pathname}/${saleOrder.id}`}
                className='flex flex-col gap-2'
              >
                <div className='flex flex-row gap-2'>
                  <div className='flex w-1/5'>
                    <Image
                      src={saleOrder.products[0]?.parent?.image}
                      alt={saleOrder.products[0]?.name}
                      className='object-contain object-center border border-gray_r-6 h-32 w-full rounded-md'
                    />
                  </div>
                  <div className='flex w-4/5 flex-col gap-2 justify-start'>
                    <p className='flex flex-row gap-2'>
                      <span className=' text-black text-sm'>Nomor PO:</span>
                      <span className=' text-red-500 font-semibold text-sm'>
                        {saleOrder.purchaseOrderName || '-'}
                      </span>
                    </p>
                    <p className='line-clamp-2 leading-6 tracking-wide opacity-90 !text-gray_r-12 font-semibold truncate text-sm'>
                      {saleOrder.products[0]?.parent?.name}
                    </p>
                    <p className='opacity-85 !text-gray_r-12'>
                      {saleOrder.products[0]?.quantity} x{' '}
                      {currencyFormat(
                        saleOrder.products[0]?.price?.priceDiscount
                      )}
                    </p>
                    <div className='flex flex-row justify-start items-center'>
                      {saleOrder.products?.length > 1 && (
                        <div className='flex flex-row gap-1 justify-start items-center'>
                          {saleOrder.products
                            .slice(1, 4)
                            .map((product, index) => (
                              <Image
                                key={index} // Tambahkan key untuk setiap elemen dalam map()
                                src={product?.parent?.image}
                                alt={product?.name}
                                className='object-contain object-center border border-gray_r-6 h-8 w-8 rounded-md'
                              />
                            ))}
                          {saleOrder.products.length > 4 ? (
                            <Link
                              href={`${router.pathname}/${saleOrder?.id}`}
                              className='text-red-500 text-nowrap'
                            >
                              +{saleOrder.products.length - 4} lihat semua
                              produk
                            </Link>
                          ) : (
                            <Link
                              href={`${router.pathname}/${saleOrder?.id}`}
                              className='text-red-500 text-nowrap'
                            >
                              Lihat semua produk
                            </Link>
                          )}
                        </div>
                      )}
                    </div>
                    <div className='flex flex-row w-full text-nowrap gap-2 text-black'>
                      <span className=''>Pesanan dibuat oleh:</span>
                      <p className=' font-semibold truncate'>
                        {saleOrder.address.customer?.name || '-'}
                      </p>
                    </div>
                  </div>
                </div>
                <div className='col-span-2 h-[1px] w-full bg-gray-300'></div>
                <div className='flex flex-col gap-3 text-sm'>
                  <div className='flex flex-col text-black'>
                    <p className='font-extralight'>Total Harga</p>
                    <p className='font-semibold text-lg'>
                      {currencyFormat(saleOrder.amountTotal)}
                    </p>
                  </div>

                  {/* Tombol aksi: vertikal & full width, responsif */}
                  <div className='flex flex-col gap-2 w-full'>
                    <button
                      type='button'
                      onClick={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        handleBuyBack(saleOrder.products);
                      }}
                      className='w-full py-2 btn-solid-red text-center rounded-md'
                    >
                      Beli Lagi
                    </button>

                    <button
                      type='button'
                      onClick={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                      }}
                      className='w-full py-2 text-center rounded-md border border-red-300 text-red-500 bg-white'
                    >
                      Lanjutkan Transaksi
                    </button>
                  </div>
                </div>

                {/* <div className='grid grid-cols-2 mt-3'>
                  <div>
                    <span className='text-caption-2 text-gray_r-11'>
                      No. Purchase Order
                    </span>
                    <p className='mt-1 font-medium text-gray_r-12'>
                      {saleOrder.purchaseOrderName || '-'}
                    </p>
                  </div>
                  <div className='text-right'>
                    <span className='text-caption-2 text-gray_r-11'>
                      Total Invoice
                    </span>
                    <p className='mt-1 font-medium text-gray_r-12'>
                      {saleOrder.invoiceCount} Invoice
                    </p>
                  </div>
                </div> */}
                {/* <div className='grid grid-cols-2 mt-3'>
                  <div>
                    <span className='text-caption-2 text-gray_r-11'>Sales</span>
                    <p className='mt-1 font-medium text-gray_r-12'>
                      {saleOrder.sales}
                    </p>
                  </div>
                  <div className='text-right'>
                    <span className='text-caption-2 text-gray_r-11'>
                      Total Harga
                    </span>
                    <p className='mt-1 font-medium text-gray_r-12'>
                      {currencyFormat(saleOrder.amountTotal)}
                    </p>
                  </div>
                </div> */}
              </Link>
            </div>
          ))}

          <Pagination
            pageCount={pageCount}
            currentPage={parseInt(pageNew)}
            // url={router.pathname + pageQuery}
            url={`${router.pathname}?${toQuery(_.omit(query, ['page']))}`}
            className='mt-2 mb-2'
          />

          <BottomPopup
            title='Lainnya'
            active={toOthers}
            close={() => setToOthers(null)}
          >
            <div className='flex flex-col gap-y-4 mt-2'>
              <button
                className='text-left disabled:opacity-60'
                disabled={!toOthers?.purchaseOrderFile}
                onClick={() => {
                  downloadPurchaseOrder(toOthers);
                  setToOthers(null);
                }}
              >
                Download PO
              </button>
              <button
                className='text-left disabled:opacity-60'
                disabled={toOthers?.status != 'draft'}
                onClick={() => {
                  downloadQuotation(toOthers);
                  setToOthers(null);
                }}
              >
                Download Quotation
              </button>
              <button
                className='text-left disabled:opacity-60'
                disabled={toOthers?.status != 'waiting'}
                onClick={() => {
                  setToCancel(toOthers);
                  setToOthers(null);
                }}
              >
                Batalkan Transaksi
              </button>
            </div>
          </BottomPopup>

          <BottomPopup
            active={toCancel}
            close={() => setToCancel(null)}
            title='Batalkan Transaksi'
          >
            <div className='leading-7 text-gray_r-12/80'>
              Apakah anda yakin membatalkan transaksi{' '}
              <span className='underline'>{toCancel?.name}</span>?
            </div>
            <div className='flex mt-6 gap-x-4'>
              <button
                className='btn-solid-red flex-1'
                type='button'
                onClick={submitCancelTransaction}
              >
                Ya, Batalkan
              </button>
              <button
                className='btn-light flex-1'
                type='button'
                onClick={() => setToCancel(null)}
              >
                Batal
              </button>
            </div>
          </BottomPopup>
        </div>
      </MobileView>

      <DesktopView>
        <div className='container mx-auto flex py-10'>
          <div className='w-3/12 pr-4'>
            <Menu />
          </div>
          <div className='w-9/12 p-4 bg-white border border-gray_r-6 rounded'>
            <div className='flex mb-6 items-center justify-between '>
              <h1 className='text-title-sm font-semibold'>
                Daftar Transaksi{' '}
                {transactions?.data?.saleOrders
                  ? `(${transactions?.data?.saleOrderTotal})`
                  : ''}
              </h1>
              <div className='relative inline-block text-left'>
                <button
                  onClick={() => setIsOpen(!isOpen)}
                  type='button'
                  className='btn-light bg-slate-50 mt-3 w-full gap-2 items-center flex flex-row !text-gray_r-11 px-4 py-3 mb-2'
                >
                  <p>Export</p>
                  <motion.div
                    animate={{ rotate: isOpen ? 180 : 0 }}
                    transition={{ duration: 0.2, ease: 'easeInOut' }}
                  >
                    <ChevronDownIcon className='w-5' />
                  </motion.div>
                </button>

                {isOpen && (
                  <motion.div
                    initial={{ opacity: 0, y: -10 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: -10 }}
                    transition={{ duration: 0.2, ease: 'easeInOut' }}
                    className='absolute mt-2 w-fit py-1 bg-white border border-gray-300 rounded-md shadow-lg'
                  >
                    <button
                      onClick={() => handleDownload('csv')}
                      className='block w-full px-4 py-2 text-left hover:bg-gray-200 text-nowrap'
                    >
                      Download CSV
                    </button>
                    <button
                      onClick={() => handleDownload('xlsx')}
                      className='block w-full px-4 py-2 text-left hover:bg-gray-200 text-nowrap'
                    >
                      Download XLSX
                    </button>
                  </motion.div>
                )}
              </div>
            </div>
            <div className=''>
              <div
                class='flex items-center p-4 mb-4 text-sm border border-yellow-500 text-yellow-800 rounded-lg bg-yellow-50'
                role='alert'
              >
                <svg
                  class='flex-shrink-0 inline w-5 h-5 mr-2'
                  aria-hidden='true'
                  fill='currentColor'
                  viewBox='0 0 20 20'
                >
                  <path d='M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5ZM9.5 4a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3ZM12 15H8a1 1 0 0 1 0-2h1v-3H8a1 1 0 0 1 0-2h2a1 1 0 0 1 1 1v4h1a1 1 0 0 1 0 2Z' />
                </svg>
                <span class='sr-only'>Info</span>
                <div className='text-justify flex flex-col gap-1'>
                  <p className='font-bold text-black'>Info Transaksi</p>
                  <span className='text-black'>
                    Gunakan filter status untuk mempermudah pencarian transaksi
                    anda di Daftar Transaksi
                  </span>
                </div>
              </div>
            </div>
            <div className='flex flex-col gap-y-2  border rounded-lg mb-2 w-full'>
              <div className='p-2'>
                <div className='flex items-center space-x-3'>
                  <span className='text-base font-semibold text-gray-600'>
                    Status
                  </span>
                  <div className='relative w-full overflow-hidden'>
                    {/* Container flex: tombol prev - swiper - tombol next */}
                    <div className='flex items-center space-x-2'>
                      {/* Prev */}
                      <button className='custom-prev w-8 h-8 flex-shrink-0 flex items-center justify-center bg-white border rounded-full shadow z-1'>
                        <svg
                          className='w-4 h-4 text-gray-500'
                          fill='none'
                          stroke='currentColor'
                          viewBox='0 0 24 24'
                        >
                          <path
                            strokeLinecap='round'
                            strokeLinejoin='round'
                            strokeWidth={2}
                            d='M15 19l-7-7 7-7'
                          />
                        </svg>
                      </button>

                      {/* Swiper container scrollable */}
                      <div className='w-full overflow-hidden'>
                        <Swiper
                          spaceBetween={10}
                          slidesPerView='auto'
                          className='status-swiper'
                          modules={[Navigation]}
                          navigation={{
                            nextEl: '.custom-next',
                            prevEl: '.custom-prev',
                          }}
                        >
                          {statuses.map((status) => (
                            <SwiperSlide key={status.id} className='!w-auto'>
                              <button
                                className={`px-4 py-1 text-sm font-medium border rounded-lg transition whitespace-nowrap
                                  ${
                                    statusNew === status.id
                                      ? 'border-red-500 text-red-500 bg-white'
                                      : 'border-gray-300 text-gray-400 bg-gray-100 hover:bg-gray-200'
                                  }`}
                                onClick={() => handleStatusChange(status.id)}
                              >
                                {status.label}
                              </button>
                            </SwiperSlide>
                          ))}
                        </Swiper>
                      </div>

                      {/* Next */}
                      <button className='custom-next w-8 h-8 flex-shrink-0 flex items-center justify-center bg-white border rounded-full shadow z-10'>
                        <svg
                          className='w-4 h-4 text-gray-500'
                          fill='none'
                          stroke='currentColor'
                          viewBox='0 0 24 24'
                        >
                          <path
                            strokeLinecap='round'
                            strokeLinejoin='round'
                            strokeWidth={2}
                            d='M9 5l7 7-7 7'
                          />
                        </svg>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
              <div className='flex flex-row items-center justify-between mb-2 p-2'>
                <div className='flex flex-col gap-2 pb-2'>
                  {listSites?.length > 0 ? (
                    <select
                      value={siteFilter}
                      onChange={handleSiteFilterChange}
                      className='form-input'
                    >
                      <option value=''>Pilih Site</option>
                      {listSites.map((site) => (
                        <option value={site} key={site}>
                          {site}
                        </option>
                      ))}
                    </select>
                  ) : (
                    <div></div>
                  )}

                  <form className='flex gap-x-1' onSubmit={handleSubmit}>
                    <input
                      type='text'
                      className='form-input'
                      placeholder='Cari Transaksi...'
                      value={inputQuery}
                      onChange={(e) => setInputQuery(e.target.value)}
                    />
                    <button
                      className='btn-light bg-transparent px-3'
                      type='submit'
                    >
                      <MagnifyingGlassIcon className='w-6' />
                    </button>
                  </form>
                </div>
                <div className='flex flex-row gap-4 items-center justify-center'>
                  <p>
                    Menampilkan {startItem}-
                    {endItem
                      ? endItem
                      : transactions?.data?.saleOrderTotal
                      ? transactions?.data?.saleOrderTotal
                      : limitNew * pageNew}{' '}
                    dari{' '}
                    {transactions?.data?.saleOrderTotal
                      ? transactions?.data?.saleOrderTotal
                      : limitNew * pageNew}
                  </p>
                  <select
                    id='limitSelect'
                    value={limitNew}
                    onChange={(e) => {
                      setLimitNew(Number(e.target.value));
                      setPageNew(1);
                    }}
                    className='border p-2'
                  >
                    <option value={10}>10</option>
                    <option value={15}>15</option>
                    <option value={20}>20</option>
                    <option value={transactions?.data?.saleOrderTotal}>
                      Semua
                    </option>
                  </select>
                  <div ref={calendarRef} className='relative inline-block'>
                    <button
                      type='button'
                      className='p-2 w-auto h-auto cursor-pointer border hover:bg-gray-100 rounded transition duration-150 ease-in-out flex items-center justify-center'
                      onClick={() => setIsOpenCalender((prev) => !prev)}
                    >
                      <span className='text-nowrap px-1 truncate flex items-center gap-1'>
                        {state[0]?.startDate ? (
                          `${state[0].startDate.toLocaleDateString()} - ${state[0].endDate.toLocaleDateString()}`
                        ) : (
                          <Calendar size={16} className='text-gray-500' />
                        )}
                      </span>
                    </button>
                    {isOpenCalender && (
                      <div className='absolute right-10 mt-2 bg-white p-4 rounded shadow-lg z-50'>
                        {/* Tombol silang di sudut kanan atas */}
                        <button
                          onClick={() => setIsOpenCalender(false)}
                          className='absolute top-2 right-2 text-gray-600 hover:text-black text-xl font-bold'
                        >
                          &times;
                        </button>
                        <DateRangePicker
                          onChange={(item) => setState([item.selection])}
                          showSelectionPreview={false}
                          maxDate={new Date()}
                          moveRangeOnFirstSelection={false}
                          months={1}
                          ranges={state}
                          className='w-full'
                        />
                        <style>{`
                        /* Atur container agar menjadi column */
                        .rdrCalendarWrapper {
                          display: flex;
                          flex-direction: column;
                        }
                        .rdrDateRangePickerWrapper  {
                          display: flex;
                          flex-direction: column;
                        }

                        /* Pindahkan rdrStaticRanges ke atas */
                        .rdrDefinedRangesWrapper {
                          order: -1;
                          width: fit-content;
                        }
                        .rdrStaticRanges {
                          flex-direction: row;
                          margin-right: 2px;
                        }

                        /* Sembunyikan bagian input manual */
                        .rdrInputRanges {
                          display: none !important;
                        }

                        .rdrStaticRangeLabel {
                          padding: 10px 10px;
                        }
                        .rdrMonth {
                          width: -moz-available;
                        }
                      `}</style>
                        <div className='flex flex-row justify-end gap-3 mt-2'>
                          <button
                            className='px-4 py-1 bg-red-500 text-white rounded'
                            onClick={handleReset}
                          >
                            Reset
                          </button>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>
            <div className='flex justify-center items-center'>
              {!transactions.isLoading &&
                transactions?.data?.saleOrders?.length == 0 && (
                  <div className='justify-center p-4'>
                    <p className='text-gray-500 text-center '>
                      Tidak Ada Transaksi
                    </p>
                  </div>
                )}

              {transactions.isLoading && (
                <div className='flex justify-center items-center my-2'>
                  <Spinner className='w-6 text-gray_r-12/50 fill-gray_r-12' />
                </div>
              )}

              {!transactions.isLoading &&
                transactions &&
                transactions.data?.saleOrders?.length > 0 && (
                  <div className='flex flex-col gap-4 w-full'>
                    {transactions.data.saleOrders.map((saleOrder, index) => (
                      <div
                        key={index}
                        className='border py-2 px-4 hover:border-red-500 w-full rounded-lg data-item'
                      >
                        <Link
                          href={`${router.pathname}/${saleOrder?.id}`}
                          className='hover:border-red-500 block w-full'
                        >
                          <div className='flex flex-row justify-between items-center py-2'>
                            <div className='flex justify-center gap-3'>
                              <TransactionStatusBadge
                                status={saleOrder.status}
                              />
                              <p className='text-red-500'>{saleOrder.name}</p>
                              <p className='text-black'>
                                Salesperson:{' '}
                                {
                                  <span className='font-semibold'>
                                    {saleOrder.sales}
                                  </span>
                                }
                              </p>
                            </div>
                            <div className='text-black'>
                              Tanggal Pesanan:{' '}
                              <span className='font-semibold'>
                                {formatDate(
                                  saleOrder.dateOrder.split(' ')[0]
                                ) || '-'}
                              </span>
                            </div>
                          </div>
                          <hr className='mt-3 mb-3 border border-gray-100' />
                          <div className='flex flex-row gap-2 justify-between items-center '>
                            <div className='flex justify-start w-3/4 flex-col gap-2'>
                              <div className='flex gap-2'>
                                <div className='min-w-36 max-w-36'>
                                  <Image
                                    src={saleOrder.products[0]?.parent?.image}
                                    alt={saleOrder.products[0]?.name}
                                    className='object-contain object-center border border-gray_r-6 h-32 w-full rounded-md'
                                  />
                                </div>
                                <div className='flex flex-col gap-3 justify-start truncate w-full'>
                                  <p className='flex flex-row gap-2'>
                                    <span className='text-sm text-black'>
                                      Nomor PO:
                                    </span>
                                    <span className='text-sm text-red-500 font-semibold'>
                                      {saleOrder.purchaseOrderName || '-'}
                                    </span>
                                  </p>
                                  <p className='line-clamp-2 leading-6 tracking-wide opacity-90 !text-gray_r-12 font-semibold text-nowrap '>
                                    {saleOrder.products[0]?.parent?.name}
                                  </p>
                                  <p className='opacity-85 !text-gray_r-12'>
                                    {saleOrder.products[0]?.quantity} x{' '}
                                    {currencyFormat(
                                      saleOrder.products[0]?.price
                                        ?.priceDiscount
                                    )}
                                  </p>
                                  <div className='flex flex-row justify-start items-center'>
                                    {saleOrder.products?.length > 1 && (
                                      <div className='flex flex-row gap-1 justify-start items-center'>
                                        {saleOrder.products
                                          .slice(1, 4)
                                          .map((product, index) => (
                                            <Image
                                              key={index} // Tambahkan key untuk setiap elemen dalam map()
                                              src={product?.parent?.image}
                                              alt={product?.name}
                                              className='object-contain object-center border border-gray_r-6 h-16 w-16 rounded-md'
                                            />
                                          ))}
                                        {saleOrder.products.length > 4 ? (
                                          <Link
                                            href={`${router.pathname}/${saleOrder?.id}`}
                                            className='text-red-500 text-nowrap'
                                          >
                                            +{saleOrder.products.length - 4}{' '}
                                            lihat semua produk
                                          </Link>
                                        ) : (
                                          <Link
                                            href={`${router.pathname}/${saleOrder?.id}`}
                                            className='text-red-500 text-nowrap'
                                          >
                                            Lihat semua produk
                                          </Link>
                                        )}
                                      </div>
                                    )}
                                  </div>
                                </div>
                              </div>
                              <div className='flex flex-row w-full text-nowrap gap-2 text-black'>
                                <span className='text-sm'>
                                  Pesanan dibuat oleh:
                                </span>
                                <p className='text-sm font-semibold'>
                                  {saleOrder.address.customer?.name || '-'}
                                </p>
                              </div>
                            </div>
                            <div className='w-[1px] h-24 bg-gray-300'></div>
                            <div className='w-1/4 flex flex-col gap-2 items-end justify-center'>
                              <div className='flex flex-col text-black w-full'>
                                <p>Total Harga</p>
                                <p className='font-bold'>
                                  {currencyFormat(saleOrder.amountTotal)}
                                </p>
                              </div>

                              <button
                                type='button'
                                onClick={(e) => {
                                  e.preventDefault();
                                  e.stopPropagation();
                                  handleBuyBack(saleOrder.products);
                                }}
                                className='w-full py-2 btn-solid-red text-nowrap rounded-md'
                              >
                                Beli Lagi
                              </button>

                              <button
                                type='button'
                                onClick={(e) => {
                                  e.preventDefault();
                                  e.stopPropagation();
                                }}
                                className='w-full py-2 btn-light text-nowrap border border-red-500 text-red-500 rounded-md'
                              >
                                Lanjutkan Transaksi
                              </button>
                            </div>
                          </div>
                        </Link>
                      </div>
                    ))}
                  </div>
                )}
            </div>
            {/* <table className='table-data'>
              <thead>
                <tr>
                  <th>No. Transaksi</th>
                  <th>No. PO</th>
                  <th>Tanggal</th>
                  <th>Created By</th>
                  {auth?.feature?.soApproval && <th>Site</th>}
                  <th className='!text-left'>Salesperson</th>
                  <th className='!text-left'>Total</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                {transactions.isLoading && (
                  <tr>
                    <td colSpan={7}>
                      <div className='flex justify-center my-2'>
                        <Spinner className='w-6 text-gray_r-12/50 fill-gray_r-12' />
                      </div>
                    </td>
                  </tr>
                )}
                {!transactions.isLoading &&
                  (!transactions?.data?.saleOrders ||
                    transactions?.data?.saleOrders?.length == 0) && (
                    <tr>
                      <td colSpan={7}>Tidak ada transaksi</td>
                    </tr>
                  )}
                {transactions.data?.saleOrders?.map((saleOrder) => (
                  <tr key={saleOrder.id}>
                    <td>
                      <Link
                        className='whitespace-nowrap'
                        href={`${router.pathname}/${saleOrder.id}`}
                      >
                        {saleOrder.name}
                      </Link>
                    </td>
                    <td>{saleOrder.purchaseOrderName || '-'}</td>
                    <td>{saleOrder.dateOrder || '-'}</td>
                    <td>{saleOrder.address.customer?.name || '-'}</td>
                    {auth?.feature?.soApproval && (
                      <td>{saleOrder.sitePartner || '-'}</td>
                    )}
                    <td className='!text-left'>{saleOrder.sales}</td>
                    <td className='!text-left'>
                      {currencyFormat(saleOrder.amountTotal)}
                    </td>
                    <td>
                      <div className='flex justify-center'>
                        <TransactionStatusBadge status={saleOrder.status} />
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table> */}

            <Pagination
              pageCount={pageCount}
              currentPage={parseInt(pageNew)}
              // url={router.pathname + (pageQuery ? `?${pageQuery}` : '')}
              url={`${router.pathname}?${toQuery(_.omit(query, ['page']))}`}
              className='mt-2 mb-2'
            />
          </div>
        </div>
      </DesktopView>
    </>
  );
};

export default Transactions;
