import React, { useEffect, useState, useContext } from 'react';
import Table from '../../components/Table/HotelTable';
import Switch from '../../components/Switch';
import { useNavigate } from 'react-router-dom';
import { langContext } from '../../context/LenguageContext';
import ConfirmationModal from '../../components/Modals/ConfirmationMontlyPay';
import '../../components/Filters/Filters.css';
import './MonthlyPayments.css';

export default function MonthlyPayments() {
  const [payments, setPayments] = useState([]);
  const [switchStates, setSwitchStates] = useState({});
  const [descriptionSearch, setDescriptionSearch] = useState('');
  const [areaFilter, setAreaFilter] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [paymentStatusFilter, setPaymentStatusFilter] = useState('');
  const [supplierFilter, setSupplierFilter] = useState('');
  const navigate = useNavigate();
  const { lang } = useContext(langContext);
  const [modalOpen, setModalOpen] = useState(false);
  const [selectedId, setSelectedId] = useState(null);
  const [taxes, setTaxes] = useState([]);
  const [selectedDescription, setselectedDescription] = useState([]);
  const [initialAmount, setInitialAmount] = useState(null);
  const [initialTaxId, setInitialTaxId] = useState(null);
  const [isFixedPayment, setIsFixedPayment] = useState(false);

  const refreshMonthlyData = async () => {
    try {
      await fetch(`${import.meta.env.VITE_API_BASE_URL}/payment/refreshmonthly`, {
        method: 'GET'
      });
    } catch (error) {
      console.error('Error refreshing monthly data:', error);
    }
  };

  const filteredData = payments.filter((item) => {
    const matchesDescription = item.description.toLowerCase().includes(descriptionSearch.toLowerCase());
    const matchesArea = !areaFilter || item.area === areaFilter;
    const matchesStatus = !statusFilter || item.status === statusFilter;
    const matchesPaymentStatus = !paymentStatusFilter || item.paymentStatus === paymentStatusFilter;
    const matchesSupplier = !supplierFilter || item.supplier === supplierFilter;
    const isPending = item.paymentStatus === "PENDING";

    return matchesDescription && matchesArea && matchesStatus && matchesPaymentStatus && matchesSupplier && isPending;
  });

  const uniqueAreas = [...new Set(payments.map(item => item.area).filter(Boolean))].sort();
  const uniqueStatuses = [...new Set(payments.map(item => item.status).filter(Boolean))].sort();
  const uniquePaymentStatuses = [...new Set(payments.map(item => item.paymentStatus).filter(Boolean))].sort();
  const uniqueSuppliers = [...new Set(payments.map(item => item.supplier).filter(Boolean))].sort();

  const clearFilters = () => {
    setDescriptionSearch('');
    setAreaFilter('');
    setStatusFilter('');
    setPaymentStatusFilter('');
    setSupplierFilter('');
  };

  const handleSwitchToggle = async (expenseId) => {
    const newState = !switchStates[expenseId];

    try {
      const response = await fetch(
        `${import.meta.env.VITE_API_BASE_URL}/payment/needtorefresh/${expenseId}`,
        {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            notrefresh: newState
          }),
        }
      );

      if (!response.ok) {
        throw new Error("Error updating refresh status");
      }

      const newStates = {
        ...switchStates,
        [expenseId]: newState
      };
      setSwitchStates(newStates);

      localStorage.setItem('recurrenceSwitchStates', JSON.stringify(newStates));

      await refreshTableData();

    } catch (error) {
      console.error("Error updating refresh status:", error);
    }
  };

  const refreshTableData = async () => {
    try {
      const response = await fetch(import.meta.env.VITE_API_BASE_URL + '/expenses/monthlypayments');
      const data = await response.json();

      const groupedDataObj = data.data.reduce((acc, item) => {
        const key = `${item.expense_description}-${item.area}`;
        const itemDate = new Date(item.payment_deadline);

        if (!acc[key] || itemDate > new Date(acc[key].payment_deadline)) {
          acc[key] = item;
        }

        return acc;
      }, {});

      const adaptedData = Object.values(groupedDataObj).map((item) => ({
        id: item.id_expense,
        description: item.expense_description,
        date: new Date(item.payment_deadline).toISOString().split('T')[0],
        area: item.area.toUpperCase(),
        recurrence: item.recurrence_name,
        supplier: item.supplier,
        status: capitalizeFirstLetter(item.status),
        amount: `$${parseFloat(item.total || 0).toLocaleString()}`,
        paymentStatus: item.status_payment.toUpperCase(),
        more: { id: item.id_expense, description: item.expense_description, status: item.status_payment }
      }));

      const groupedData = adaptedData.sort((a, b) => {
        if (a.paymentStatus === "PENDING" && b.paymentStatus !== "PENDING") return -1;
        if (a.paymentStatus !== "PENDING" && b.paymentStatus === "PENDING") return 1;

        const descCompare = a.description.localeCompare(b.description);
        if (descCompare !== 0) return descCompare;

        const areaCompare = a.area.localeCompare(b.area);
        if (areaCompare !== 0) return areaCompare;

        return 0;
      });

      setPayments(groupedData);
    } catch (error) {
      console.error('Error refreshing table data:', error);
    }
  };

  const handleOpenModal = async (more) => {
    const {id, description} = more;
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/payment/onemothlyexpense/${id}`);
    const data = await response.json();
    setSelectedId(id);
    setselectedDescription(description);
    
    if (data.data && data.data[0] && data.data[0].payment_type === 1) {
      setInitialAmount(data.data[0].new_subtotal);
      setInitialTaxId(data.data[0].tax_id);
      setIsFixedPayment(true);
    } else {
      setInitialAmount(null);
      setInitialTaxId(null);
      setIsFixedPayment(false);
    }
    
    setModalOpen(true);
  };
  const handleConfirm = async (taxid, amount) => {
    console.log(taxid, amount, selectedId);

    try {
      const response = await fetch(
        `${import.meta.env.VITE_API_BASE_URL}/payment/paymentstatusmonthly/${selectedId}`,
        {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            status_payment: 1,
            tax_id: taxid,
            subtotal: amount,
          }),
        }
      );

      if (!response.ok) {
        throw new Error("Error al aplicar el cambio");
      }

      const data = await response.json();
      console.log("✅ Respuesta del servidor:", data);

      await refreshMonthlyData();

      await refreshTableData();

    } catch (err) {
      console.error("❌ Error en handleConfirm:", err);
    }
  };

  const handleCancel = () => {
    setModalOpen(false);
  };


  useEffect(() => {
    const loadData = async () => {
      await refreshMonthlyData();

      async function MP() {
      await fetch(import.meta.env.VITE_API_BASE_URL + '/expenses/monthlypayments')
        .then((response) => response.json())
        .then((data) => {
          const groupedDataObj = data.data.reduce((acc, item) => {
            const key = `${item.expense_description}-${item.area}`;
            const itemDate = new Date(item.payment_deadline);

            if (!acc[key] || itemDate > new Date(acc[key].payment_deadline)) {
              acc[key] = item;
            }

            return acc;
          }, {});

          const adaptedData = Object.values(groupedDataObj).map((item) => ({
            id: item.id_expense,
            description: item.expense_description,
            date: new Date(item.payment_deadline).toISOString().split('T')[0],
            area: item.area.toUpperCase(),
            recurrence: item.recurrence_name,
            supplier: item.supplier,
            status: capitalizeFirstLetter(item.status),
            amount: `$${parseFloat(item.total || 0).toLocaleString()}`,
            paymentStatus: item.status_payment.toUpperCase(),
            more: { id: item.id_expense, description: item.expense_description, status: item.status_payment }
          }));

          const groupedData = adaptedData.sort((a, b) => {
            if (a.paymentStatus === "PENDING" && b.paymentStatus !== "PENDING") return -1;
            if (a.paymentStatus !== "PENDING" && b.paymentStatus === "PENDING") return 1;

            const descCompare = a.description.localeCompare(b.description);
            if (descCompare !== 0) return descCompare;

            const areaCompare = a.area.localeCompare(b.area);
            if (areaCompare !== 0) return areaCompare;

            return 0;
          });

          setPayments(groupedData);

          const savedStates = JSON.parse(localStorage.getItem('recurrenceSwitchStates') || '{}');
          const initialStates = {};
          groupedData.forEach(expense => {
            initialStates[expense.id] = savedStates[expense.id] !== undefined ? savedStates[expense.id] : true;
          });
          setSwitchStates(initialStates);
        })
        .catch((error) => {
          console.error('Error fetching monthly payments:', error);
        });
    }
    async function Impuestos() {
      await fetch(import.meta.env.VITE_API_BASE_URL + '/expenses/getinfo')
        .then(res => res.json())
        .then(data => {
          setTaxes(data.tax);
        })
        .catch(err => console.error('Error fetching suppliers', err));
      }

      MP();
      Impuestos();
    };

    loadData();
  }, []);

  const columns = [
    {
      header: lang === "en" ? "ACTIVE" : "ACTIVO",
      key: 'active',
      render: (value, row) => (
        <Switch
          checked={switchStates[row.id] ?? true}
          onChange={() => handleSwitchToggle(row.id)}
        />
      ),
    },
    { header: lang === "en" ? "EXPENSE DESCRIPTION" : "DESCRIPCIÓN DEL GASTO", key: 'description' },
    { 
      header: lang === "en" ? "PAYMENT DEADLINE" : "FECHA LÍMITE DE PAGO", 
      key: 'date',
      render: (date, row) => (
        <span style={{ color: row.status.toLowerCase() === 'delay' ? 'red' : 'inherit' }}>
          {date}
        </span>
      )
    },
    { header: lang === "en" ? "AREA" : "ÁREA", key: 'area' },
    { header: lang === "en" ? "RECURRENCE" : "RECURRENCIA", key: 'recurrence' },
    { header: lang === "en" ? "SUPPLIER" : "PROVEEDOR", key: 'supplier' },
    { header: lang === "en" ? "STATUS" : "ESTADO", key: 'status' },
    { header: lang === "en" ? "AMOUNT" : "IMPORTE", key: 'amount' },
    {
      header: lang === "en" ? "PAYMENT STATUS" : "ESTADO DE PAGO",
      key: 'paymentStatus',
      headerStyle: { textAlign: 'center' },
      render: (status) => (
        <div style={{ textAlign: 'center' }}>
          <button className={`status-button ${status.toLowerCase()}`}>
            {status}
          </button>
        </div>
      ),
    },
    {
      header: lang === "en" ? "PAID" : "PAGAR",
      key: 'more',
      headerStyle: { textAlign: 'center' },
      render: (more) => (
        <div style={{ display: 'flex', gap: '10px', justifyContent: 'center' }}>
          <button
            className={more.status !== "PAID" && more.status !== "REJECTED" ? "status-badge active" : "status-badge deactive"}
            onClick={() => handleOpenModal(more)}
            disabled={more.status === "PAID" || more.status === "REJECTED"}
          >
            {lang === "en" ? "PAID" : "PAGAR"}
          </button>

        </div>
      ),
    },

  ];

  function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
  }

  return (
    <div className="monthly-payments-page">
      <div className="page-header">
        <h2 className="page-title">
          {lang === "en" ? "Monthly payments" : "Pagos mensuales"}
        </h2>
        <button
          className="new-payment-btn"
          onClick={() => navigate('/app/new-monthly')}
        >
          {lang === "en" ? "New monthly payment" : "Nuevo pago mensual"}
        </button>
      </div>

      <div className="page-filters">
        <div className="filters-row">
          <input
            type="text"
            value={descriptionSearch}
            onChange={(e) => setDescriptionSearch(e.target.value)}
            placeholder={lang === "en" ? "Search by description..." : "Buscar por descripción..."}
            className="filter-search"
          />

          <select
            value={areaFilter}
            onChange={(e) => setAreaFilter(e.target.value)}
            className="filter-select"
          >
            <option value="">{lang === "en" ? "All Areas" : "Todas las Áreas"}</option>
            {uniqueAreas.map((area, index) => (
              <option key={index} value={area}>{area}</option>
            ))}
          </select>

          <select
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
            className="filter-select"
          >
            <option value="">{lang === "en" ? "All Statuses" : "Todos los Estados"}</option>
            {uniqueStatuses.map((status, index) => (
              <option key={index} value={status}>{status}</option>
            ))}
          </select>
        </div>

        <div className="filters-row second-row">
          <select
            value={paymentStatusFilter}
            onChange={(e) => setPaymentStatusFilter(e.target.value)}
            className="filter-select"
          >
            <option value="">{lang === "en" ? "All Payment Statuses" : "Todos los Estados de Pago"}</option>
            {uniquePaymentStatuses.map((status, index) => (
              <option key={index} value={status}>{status}</option>
            ))}
          </select>

          <select
            value={supplierFilter}
            onChange={(e) => setSupplierFilter(e.target.value)}
            className="filter-select"
          >
            <option value="">{lang === "en" ? "All Suppliers" : "Todos los Proveedores"}</option>
            {uniqueSuppliers.map((supplier, index) => (
              <option key={index} value={supplier}>{supplier}</option>
            ))}
          </select>

          <button
            onClick={clearFilters}
            className="clear-filters-btn"
          >
            {lang === "en" ? "Clear Filters" : "Limpiar Filtros"}
          </button>
        </div>
      </div>

      <div className="table-section">
        <Table columns={columns} data={filteredData} />
      </div>

      <ConfirmationModal
        isOpen={modalOpen}
        onConfirm={handleConfirm}
        onCancel={handleCancel}
        description={selectedDescription}
        taxes={taxes}
        initialAmount={initialAmount}
        initialTaxId={initialTaxId}
        isFixedPayment={isFixedPayment}
      />
    </div>
  );
}
