import React, { useEffect, useState, useCallback } from 'react';
import { Select, Button, TextField, Box } from '@shopify/polaris';
import { useAuthenticatedFetch } from '../hooks';

function Checkout() {
  let fetch = useAuthenticatedFetch();
  let [collections, setCollections] = useState();
  let [collectionsId, setCollectionsId] = useState('0');

  let [locations, setLocations] = useState();
  let [locationsId, setLocationsId] = useState('0');

  const [email, setEmail] = useState('');

  useEffect(() => {
    const fetchCollectionData = async () => {
      try {
        let request = await fetch("/api/collections/all");
        let response = await request.json();
        setCollections(response.data);
      } catch (error) {
        console.error('Error fetching collection data:', error);
      }
    };
    const fetchLocationData = async () => {
      try {
        let request = await fetch("/api/pickup/location");
        let response = await request.json();
        setLocations(response.data);
        console.log('Location : ', response.data);
      } catch (error) {
        console.error('Error fetching collection data:', error);
      }
    };

    fetchCollectionData();
    fetchLocationData();
  }, []);

  const handleSelectCollection = useCallback(
    (value) => setCollectionsId(value),
    [],
  );

  const handleSelectLocation = useCallback(
    (value) => setLocationsId(value),
    [],
  );

  let collection = [];
  if (Array.isArray(collections)) {
    collection.push({ value: '0', id: '0', label: 'Select your collection type' });
    collection = collection.concat(collections.map(collection => ({
      label: collection.title,
      value: collection.id.toString(), // Convert ID to string
    })));
  }

  let location = [];
  if (Array.isArray(locations)) {
    location.push({ value: '0', id: '0', label: 'Select your location type' });
    location = location.concat(locations.map(location => ({
      label: location.name,
      value: location.id.toString(), // Convert ID to string
    })));
  }

  const [rows, setRows] = useState([]);
  const handleEmailChange = (newValue) => {
    setEmail(newValue);
  };

  const handleSave = async () => {
    try {
      const response = await fetch('/api/savedata', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          collection_id: collectionsId,
          location_id: locationsId,
          email: email,
        }),
      });

      if (response.ok) {
        // Data successfully saved
        console.log('Data saved successfully!');
      } else {
        // Error handling
        console.error('Failed to save data:', response.statusText);
      }
    } catch (error) {
      console.error('Error saving data:', error);
    }
  };

  const handleSaveMultiple = async () => {
    try {

      const isValid = rows.every(row => (
        row.collection_id && row.location_id && row.email 
      ));

      if (!isValid) {
        console.error('Please fill in all required fields.');
        alert('Please fill in all required fields.');
        return; 
      }
      const duplicates = findDuplicateRows();
      if (duplicates.length>0) {
        console.log('duplicate : ',duplicates);
        alert(`Duplicate row : The email '${duplicates[0].email}' already exists.`);
        // alert(`Duplicate row : The email already exists.`);
        return;
      }

      const response = await fetch('/api/savedata/multipledata', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(rows),
      });
      if (response.ok) {
        console.log('Multiple Data saved successfully!');

        FetchData();
      } else {
        console.error('Failed to save data:', response.statusText);
      }
    } catch (error) {
      console.error('Error saving data:', error);
    }
  };

  const findDuplicateRows = () => {
    const duplicateRows = rows.filter((row, index) => (
      rows.some((otherRow, otherIndex) => (
        index !== otherIndex && // Exclude comparing the same row
        row.collection_id === otherRow.collection_id &&
        row.location_id === otherRow.location_id &&
        row.email === otherRow.email
      ))
    ));
  
    return duplicateRows;
  };
  


  const FetchData = async () => {
    try {
      const response = await fetch('/api/getdata', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });
      if (response.ok) {
        const data = await response.json();
        const initialRows = data.map(data => ({
          id: data._id,
          collection_id: data.collection_id,
          location_id: data.location_id,
          email: data.email
        }));
        setRows(initialRows);
        console.log('Data fetched successfully:', data);
      } else {
        console.error('Failed to fetch data:', response.statusText);
      }
    } catch (error) {
      console.error('Error fetch data:', error);
    }
  };

  const removeRows = async (removeId) => {
    try {
      const response = await fetch('/api/removedata', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          _id: removeId
        }),
      });

      if (response.ok) {
        console.log('Data Remove successfully!');
        const updatedRows = rows.slice(0, -1);
        console.log('updatedRows Rows : ',updatedRows);
        setRows(updatedRows);
      } else {
        // Error handling
        console.error('Failed to save data:', response.statusText);
      }
    } catch (error) {
      console.error('Error saving data:', error);
    }
  };

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


  console.log('test Rows : ', rows);

  const handleDuplicateRow = () => {
    const newRow = { collection_id: '', location_id: '', email: '' }; // Create a new empty row
    setRows([...rows, newRow]); // Append the new row to the list of rows
  };



  const handleRowChange = (index, field, value) => {
    const newRows = [...rows]; // Copy the current state
    newRows[index][field] = value; // Update the specific field of the specific row
    setRows(newRows); // Update the state with the modified rows
  };

  if (rows.length == 0) {
    console.log('Data not found');
    handleDuplicateRow();
  }

  const RemoveDuplicateRow = () => {
    const removedRow = rows[rows.length - 1];

    if(removedRow.id){
      console.log('Remove Rows : ',removedRow.id);
      removeRows(removedRow.id);
    }else{
      const updatedRows = rows.slice(0, -1);
      console.log('updatedRows Rows : ',updatedRows);
      setRows(updatedRows);
    }

  
  };



  return (
    <div>
      {/* old */}
      {/* <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', marginTop: '10px', marginLeft: '10px' }}>
          <div style={{ marginRight: '10px' }}>
            <Select
              label="Select your Collection"
              options={collection || []}
              onChange={handleSelectCollection}
              value={collectionsId}
            />
          </div>
          <div style={{ marginRight: '10px' }}>
            <Select
              label="Select Your Pickup location"
              options={location || []}
              onChange={handleSelectLocation}
              value={locationsId}
            />
          </div>
          <div>
            <TextField
              label="Email Address"
              name="email"
              value={email}
              onChange={handleEmailChange}
            />
          </div>

          <div style={{ marginBottom: '0px', marginLeft: '10px', marginTop: '10px' }}>
            <Button onClick={handleSave}>Save</Button>
          </div>
        </div> */}


      {rows.map((row, index) => (
        <div key={index}>
          <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', marginTop: '10px', marginLeft: '10px' }}>
            <div style={{ marginRight: '10px' }}>
              <Select
                label="Select Collection"
                name={`collection_id_${index}`}
                options={collection}
                onChange={(value) => handleRowChange(index, 'collection_id', value)}
                value={row.collection_id}
              />
            </div>
            <div style={{ marginRight: '10px' }}>
              <Select
                label="Select Location"
                name={`location_id_${index}`}
                options={location}
                onChange={(value) => handleRowChange(index, 'location_id', value)}
                value={row.location_id}
              />
            </div>
            <div style={{ marginRight: '10px' }}>
              <TextField
                label="Email"
                value={row.email}
                onChange={(newValue) => handleRowChange(index, 'email', newValue)}
              />
            </div>
            {index === rows.length - 1 && (
              <div style={{ display: 'flex', flexDirection: 'row' }}>
                <Box as="div" style={{ marginTop: '20px', marginLeft: '10px' }}>
                  <Button onClick={handleDuplicateRow}>+</Button>
                </Box>

                <Box as="div" style={{ marginTop: '20px', marginLeft: '10px' }}>
                  <Button onClick={RemoveDuplicateRow}>-</Button>
                </Box>
              </div>


            )}
          </div>
        </div>
      ))}

      <div style={{ marginBottom: '0px', marginLeft: '10px', marginTop: '10px' }}>
        <Button onClick={handleSaveMultiple}>Multiple Save Data</Button>
      </div>


    </div>
  );
}

export default Checkout;
