import * as React from "react";
import { useState } from "react";
import {
  Box,
  Typography,
  TextField,
  Button,
  Paper,
  Alert,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Checkbox,
  FormControlLabel,
} from "@mui/material";
import { SelectChangeEvent } from "@mui/material/Select";
import { postProduct } from "./adminAPIservices";
import Layout from "./adminlayout";

const mockCategories = [
  { id: 1, name: "Sofas" },
  { id: 2, name: "Chairs" },
  { id: 3, name: "Tables" },
  { id: 4, name: "Beds" },
];

const mockBrands = [
  { id: 1, name: "IKEA" },
  { id: 2, name: "Ashley" },
  { id: 3, name: "Herman Miller" },
  { id: 4, name: "West Elm" },
];

interface ProductFormData {
  name: string;
  description: string;
  category_id: number;
  brand_id: number;
  is_active: boolean;
}

const ProductForm: React.FC = () => {
  const [formData, setFormData] = useState<ProductFormData>({
    name: "",
    description: "",
    category_id: 1,
    brand_id: 1,
    is_active: true,
  });
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState("");

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const handleSelectChange = (e: SelectChangeEvent<number>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value as number }));
  };

  const handleCheckboxChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, checked } = e.target;
    setFormData((prev) => ({ ...prev, [name]: checked }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError("");
    setSuccess(false);

    try {
      const result = await postProduct(formData);
      if (result.success) {
        setSuccess(true);
        setFormData({
          name: "",
          description: "",
          category_id: 1,
          brand_id: 1,
          is_active: true,
        });
      } else {
        setError(result.error || "Failed to create product");
      }
    } catch (err) {
      setError("An unexpected error occurred");
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      <Box sx={{ mb: 4 }}>
        <Typography variant="h4" gutterBottom>
          Add New Product
        </Typography>
        <Typography variant="body1" color="text.secondary">
          Manage furniture products for your e-commerce store
        </Typography>
      </Box>

      <Paper sx={{ p: 3, mb: 3 }}>
        {error && (
          <Alert severity="error" sx={{ mb: 3 }}>
            {error}
          </Alert>
        )}
        {success && (
          <Alert severity="success" sx={{ mb: 3 }}>
            Product created successfully!
          </Alert>
        )}

        <form onSubmit={handleSubmit}>
          <TextField
            fullWidth
            label="Product Name"
            name="name"
            value={formData.name}
            onChange={handleInputChange}
            margin="normal"
            required
          />
          <TextField
            fullWidth
            label="Description"
            name="description"
            value={formData.description}
            onChange={handleInputChange}
            margin="normal"
            multiline
            rows={4}
          />

          <FormControl fullWidth margin="normal">
            <InputLabel>Category</InputLabel>
            <Select
              name="category_id"
              value={formData.category_id}
              onChange={handleSelectChange}
              label="Category"
            >
              {mockCategories.map((category) => (
                <MenuItem key={category.id} value={category.id}>
                  {category.name}
                </MenuItem>
              ))}
            </Select>
          </FormControl>

          <FormControl fullWidth margin="normal">
            <InputLabel>Brand</InputLabel>
            <Select
              name="brand_id"
              value={formData.brand_id}
              onChange={handleSelectChange}
              label="Brand"
            >
              {mockBrands.map((brand) => (
                <MenuItem key={brand.id} value={brand.id}>
                  {brand.name}
                </MenuItem>
              ))}
            </Select>
          </FormControl>

          <FormControlLabel
            control={
              <Checkbox
                name="is_active"
                checked={formData.is_active}
                onChange={handleCheckboxChange}
                color="primary"
              />
            }
            label="Active Product"
            sx={{ mt: 2 }}
          />

          <Box sx={{ mt: 3 }}>
            <Button
              type="submit"
              variant="contained"
              color="primary"
              disabled={loading}
              size="large"
            >
              {loading ? "Creating..." : "Create Product"}
            </Button>
          </Box>
        </form>
      </Paper>
    </>
  );
};

export default ProductForm;
