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

const FormContainer = styled.div`
  background: white;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  border-radius: 1rem;
  padding: 2rem;
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  position: relative;
`;

const FormTitle = styled.h2`
  font-size: 1.8rem;
  font-weight: bold;
  margin-bottom: 1.5rem;
`;

const FormDescription = styled.p`
  font-size: 1rem;
  color: #6b7280;
  margin-bottom: 1.5rem;
`;

const Form = styled.form`
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
`;

const FormField = styled.div`
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
`;

const Label = styled.label`
  font-size: 1rem;
  font-weight: 600;
  color: #374151;
`;

const Input = styled.input`
  padding: 0.75rem;
  font-size: 1rem;
  border: 1px solid #d1d5db;
  border-radius: 0.5rem;
  background-color: #f9fafb;
  color: #374151;

  &:focus {
    outline: none;
    border-color: #4f46e5;
    background-color: #fff;
  }
`;

const ColorInput = styled.input`
  padding: 0.25rem;
  width: 80px;
  height: 40px;
  border: 1px solid #d1d5db;
  border-radius: 0.5rem;
  cursor: pointer;
`;

const Button = styled.button`
  padding: 1rem;
  background: #4f46e5;
  color: white;
  font-weight: bold;
  border: none;
  border-radius: 0.5rem;
  cursor: pointer;
  transition: 0.3s;
  width: 200px;
  display: flex;
  justify-content: center;
  align-items: center;

  &:hover {
    background: #4338ca;
  }

  &:disabled {
    background: #d1d5db;
    cursor: not-allowed;
  }
`;

const LoadingSpinner = styled.div`
  border: 4px solid #f3f3f3;
  border-top: 4px solid #4f46e5;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  animation: spin 2s linear infinite;
  
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
`;

const CreateOrderStatus = ({ status, onNotification }) => {
  const [statusName, setStatusName] = useState('');
  const [statusSlug, setStatusSlug] = useState('');
  const [dashicon, setDashicon] = useState('');
  const [statusColor, setStatusColor] = useState('#f8dda7');
  const [loading, setLoading] = useState(false);
  const [isUpdateMode, setIsUpdateMode] = useState(false);

  useEffect(() => {
    if (status) {
      setStatusName(status.statusName);
      setStatusSlug(status.statusSlug);
      setDashicon(status.dashicon);
      setStatusColor(status.statusColor);
      setIsUpdateMode(true);
    }
  }, [status]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);

    const postData = {
        statusName,
        statusSlug,
        dashicon,
        statusColor,
    };

    // Store the original slug for update URL
    const originalSlug = status?.statusSlug || statusSlug;

    // Update this URL construction using the original slug for edit mode
    const siteUrl = isUpdateMode 
        ? `${window.AOSFW_APP.root}asofw/v1/edit-status/${originalSlug}`
        : `${window.AOSFW_APP.root}asofw/v1/create-status`;

    try {
        console.log('Making request to:', siteUrl); // Debug URL
        console.log('Request data:', postData); // Debug data

        const response = await fetch(siteUrl, {
            method: isUpdateMode ? 'PUT' : 'POST',
            headers: {
                'X-WP-Nonce': window.AOSFW_APP.nonce,
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(postData),
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.message || 'Failed to process request');
        }

        const data = await response.json();
        onNotification(data.message, 'success');
        
        // Reset form and update mode after successful operation
        if (!isUpdateMode) {
            setStatusName('');
            setStatusSlug('');
            setDashicon('');
            setStatusColor('#f8dda7');
        }
    } catch (error) {
        console.error('Error:', error);
        onNotification(error.message || 'Failed to process request', 'error');
    } finally {
        setLoading(false);
    }
};

  return (
    <FormContainer>
      <FormTitle>{isUpdateMode ? 'Update Order Status' : 'Create Order Status'}</FormTitle>
      <FormDescription>
        {isUpdateMode
          ? 'Update the details of the custom order status.'
          : 'Create a new custom order status.'}
      </FormDescription>

      <Form onSubmit={handleSubmit}>
        {/* Status Name Field */}
        <FormField>
          <Label htmlFor="statusName">Status Name</Label>
          <Input
            type="text"
            id="statusName"
            name="statusName"
            value={statusName}
            onChange={(e) => setStatusName(e.target.value)}
            placeholder="Enter status name"
            required
          />
        </FormField>

        {/* Status Slug Field */}
        <FormField>
          <Label htmlFor="statusSlug">Status Slug</Label>
          <Input
            type="text"
            id="statusSlug"
            name="statusSlug"
            value={statusSlug}
            onChange={(e) => setStatusSlug(e.target.value)}
            placeholder="Enter status slug"
            required
          />
        </FormField>

        {/* Dashicon Field */}
        <FormField>
          <Label htmlFor="dashicon">Dashicon Class</Label>
          <Input
            type="text"
            id="dashicon"
            name="dashicon"
            value={dashicon}
            onChange={(e) => setDashicon(e.target.value)}
            placeholder="e.g., dashicons-cart"
            required
          />
        </FormField>

        {/* Status Color Field */}
        <FormField>
          <Label htmlFor="statusColor">Status Color</Label>
          <ColorInput
            type="color"
            id="statusColor"
            name="statusColor"
            value={statusColor}
            onChange={(e) => setStatusColor(e.target.value)}
          />
        </FormField>

        {/* Submit Button */}
        <FormField>
          <Button type="submit" disabled={loading}>
            {loading ? <LoadingSpinner /> : isUpdateMode ? 'Update Order Status' : 'Create Order Status'}
          </Button>
        </FormField>
      </Form>
    </FormContainer>
  );
};

export default CreateOrderStatus;
