// BrandPage.tsx
import React, { useState, useEffect } from "react";
import {
  Box,
  Typography,
  TextField,
  Button,
  Paper,
  Alert,
  Grid,
  Card,
  CardContent,
  CardMedia,
  Link,
  Chip,
} from "@mui/material";
import { Add, Public } from "@mui/icons-material";
import { postBrand, getBrands } from "./adminAPIservices";

const BrandPage = () => {
  const [formData, setFormData] = useState({
    name: "",
    description: "",
    website: "",
  });
  const [brands, setBrands] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);

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

  const fetchBrands = async () => {
    const result = await getBrands();
    if (result.success) setBrands(result.data);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    const result = await postBrand(formData);
    if (result.success) {
      setFormData({ name: "", description: "", website: "" });
      fetchBrands();
    }
    setLoading(false);
  };

  return (
    <Box sx={{ p: 3 }}>
      <Typography
        variant="h4"
        gutterBottom
        sx={{ mb: 3, color: "primary.main" }}
      >
        Brand Management
      </Typography>

      <Grid container spacing={3}>
        <Grid item xs={12} md={4}>
          <Paper elevation={3} sx={{ p: 3, borderRadius: 2 }}>
            <Typography variant="h6" gutterBottom>
              Add New Brand
            </Typography>
            <form onSubmit={handleSubmit}>
              <TextField
                fullWidth
                label="Brand Name"
                name="name"
                value={formData.name}
                onChange={(e) =>
                  setFormData({ ...formData, name: e.target.value })
                }
                margin="normal"
                required
              />
              <TextField
                fullWidth
                label="Description"
                name="description"
                value={formData.description}
                onChange={(e) =>
                  setFormData({ ...formData, description: e.target.value })
                }
                margin="normal"
                multiline
                rows={3}
              />
              <TextField
                fullWidth
                label="Website"
                name="website"
                value={formData.website}
                onChange={(e) =>
                  setFormData({ ...formData, website: e.target.value })
                }
                margin="normal"
                type="url"
              />
              <Button
                type="submit"
                variant="contained"
                color="primary"
                startIcon={<Add />}
                sx={{ mt: 2 }}
                disabled={loading}
              >
                {loading ? "Creating..." : "Create Brand"}
              </Button>
            </form>
          </Paper>
        </Grid>

        <Grid item xs={12} md={8}>
          <Typography variant="h6" gutterBottom sx={{ mb: 2 }}>
            Brand Directory ({brands.length})
          </Typography>

          <Grid container spacing={2}>
            {brands.map((brand) => (
              <Grid item xs={12} sm={6} md={4} key={brand.id}>
                <Card
                  sx={{
                    height: "100%",
                    display: "flex",
                    flexDirection: "column",
                    boxShadow: 3,
                    "&:hover": { boxShadow: 6 },
                  }}
                >
                  <CardMedia
                    component="div"
                    sx={{
                      pt: "56.25%", // 16:9 ratio
                      background: `linear-gradient(45deg, ${stringToColor(
                        brand.name
                      )} 30%, ${stringToHoverColor(brand.name)} 90%)`,
                    }}
                  />
                  <CardContent>
                    <Typography gutterBottom variant="h6" component="div">
                      {brand.name}
                    </Typography>
                    <Typography
                      variant="body2"
                      color="text.secondary"
                      sx={{ mb: 1 }}
                    >
                      {brand.description || "No description"}
                    </Typography>
                    {brand.website && (
                      <Link href={brand.website} target="_blank" rel="noopener">
                        <Chip
                          icon={<Public fontSize="small" />}
                          label="Website"
                          clickable
                          color="primary"
                          size="small"
                        />
                      </Link>
                    )}
                  </CardContent>
                </Card>
              </Grid>
            ))}
          </Grid>
        </Grid>
      </Grid>
    </Box>
  );
};

// Helper functions for card colors
function stringToColor(string: string) {
  let hash = 0;
  for (let i = 0; i < string.length; i++) {
    hash = string.charCodeAt(i) + ((hash << 5) - hash);
  }
  let color = "#";
  for (let i = 0; i < 3; i++) {
    const value = (hash >> (i * 8)) & 0xff;
    color += `00${value.toString(16)}`.slice(-2);
  }
  return color;
}

function stringToHoverColor(string: string) {
  return `${stringToColor(string)}80`; // Add opacity
}

export default BrandPage;
