import React, { useState, useEffect } from 'react';
import styled from 'styled-components';

const TableContainer = styled.div`
  background: white;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  border-radius: 1rem;
  padding: 2rem;
  width: 100%;
`;

const Table = styled.table`
  width: 100%;
  border-collapse: collapse;
`;

const TableHeader = styled.th`
  padding: 1rem;
  background: #4f46e5;
  color: white;
  font-weight: bold;
`;

const TableRow = styled.tr`
  border-bottom: 1px solid #e5e7eb;
`;

const TableData = styled.td`
  padding: 1rem;
  text-align: center;
`;

const TableActions = styled.div`
  display: flex;
  justify-content: center;
  gap: 1rem;
`;

const EditButton = styled.button`
  padding: 0.5rem;
  background: #4f46e5;
  color: white;
  border-radius: 0.5rem;
  cursor: pointer;
  border: none;
`;

const DeleteButton = styled.button`
  padding: 0.5rem;
  background: #dc2626;
  color: white;
  border-radius: 0.5rem;
  cursor: pointer;
  border: none;
`;

const CustomOrderStatus = ({ onEdit, onNotification }) => {
  const [statuses, setStatuses] = useState([]);
  const [loading, setLoading] = useState(true);

  const fetchStatuses = async () => {
    try {
      const response = await fetch(`${window.AOSFW_APP.root}asofw/v1/statuses`, {
        method: 'GET',
        headers: {
          'X-WP-Nonce': window.AOSFW_APP.nonce,
        },
      });

      if (!response.ok) {
        throw new Error('Failed to fetch statuses');
      }

      const data = await response.json();
      
      // Convert the object to array with slug as the key
      const formattedStatuses = Object.entries(data).map(([slug, details]) => ({
        statusSlug: slug,
        ...details
      }));

      setStatuses(formattedStatuses);
    } catch (error) {
      console.error('Error fetching statuses:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const handleDelete = async (statusSlug) => {
    if (window.confirm('Are you sure you want to delete this status?')) {
      try {
        const response = await fetch(
          `${window.AOSFW_APP.root}asofw/v1/delete-status/${statusSlug}`,
          {
            method: 'DELETE',
            headers: {
              'X-WP-Nonce': window.AOSFW_APP.nonce,
            },
          }
        );

        if (!response.ok) {
          throw new Error('Failed to delete status');
        }

        const data = await response.json();
        onNotification(data.message, 'success');
        await fetchStatuses();
      } catch (error) {
        console.error('Error deleting status:', error);
        onNotification(error.message || 'Failed to delete status', 'error');
      }
    }
  };

  const handleEdit = async (status) => {
    try {
        const url = `${window.AOSFW_APP.root}asofw/v1/edit-status/${status.statusSlug}`;
        console.log('Making request to:', url); // Debug URL

        const response = await fetch(url, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'X-WP-Nonce': window.AOSFW_APP.nonce,
            },
            body: JSON.stringify({
                statusName: status.statusName,
                dashicon: status.dashicon,
                statusColor: status.statusColor
            }),
        });

        console.log('Response status:', response.status); // Debug response

        if (!response.ok) {
            const errorData = await response.json();
            console.log('Error data:', errorData); // Debug error
            throw new Error(errorData.message || 'Failed to update status');
        }

        const data = await response.json();
        alert(data.message);
        await fetchStatuses();

    } catch (error) {
        console.error('Error updating status:', error);
        alert(error.message || 'Failed to update status. Please try again.');
    }
};

  if (loading) {
    return <div>Loading...</div>;
  }

  if (!statuses.length) {
    return <div>No custom order statuses found.</div>;
  }

  return (
    <TableContainer>
      <Table>
        <thead>
          <tr>
            <TableHeader>Status Name</TableHeader>
            <TableHeader>Dashicon</TableHeader>
            <TableHeader>Status Color</TableHeader>
            <TableHeader>Actions</TableHeader>
          </tr>
        </thead>
        <tbody>
          {statuses.map((status) => (
            <TableRow key={status.statusSlug}>
              <TableData>{status.statusName}</TableData>
              <TableData>
                <span className={`dashicons ${status.dashicon}`}></span>
              </TableData>
              <TableData>
                <div
                  style={{
                    width: '20px',
                    height: '20px',
                    backgroundColor: status.statusColor,
                    borderRadius: '50%',
                    margin: '0 auto'
                  }}
                ></div>
              </TableData>
              <TableData>
                <TableActions>
                  <EditButton onClick={() => onEdit(status)}>Edit</EditButton>
                  <DeleteButton onClick={() => handleDelete(status.statusSlug)}>
                    Delete
                  </DeleteButton>
                </TableActions>
              </TableData>
            </TableRow>
          ))}
        </tbody>
      </Table>
    </TableContainer>
  );
};

export default CustomOrderStatus;
