// Components.jsx
import React, { useState, useContext } from "react";
import {
  Paper,
  IconButton,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  Grid,
  Box,
  Typography,
  Card,
  CardActionArea,
  CardContent,
  Switch,
  FormControlLabel,
  Tabs,
  Tab,
  Select,
  MenuItem,
  Slider,
} from "@mui/material";
import { motion, AnimatePresence } from "framer-motion";
import SettingsIcon from "@mui/icons-material/Settings";
import AddIcon from "@mui/icons-material/Add";
import { Theme, ThemeContext } from "./Theme";
import {
  useWindowManager,
  WindowManagerProvider,
} from "./contexts/WindowManagerContext";
import { WindowManager } from "./WindowManager";

// Utility function to convert hex to rgb
const hexToRgb = (hex) => {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result
    ? `${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt(
        result[3],
        16
      )}`
    : "33, 150, 243";
};

// TabPanel Component
export const TabPanel = ({ children, value, index, ...other }) => (
  <div role="tabpanel" hidden={value !== index} {...other}>
    {value === index && <Box sx={{ p: 3 }}>{children}</Box>}
  </div>
);

// SettingsModal Component
export const SettingsModal = ({ open, onClose }) => {
  const [tab, setTab] = useState(0);
  const {
    currentTheme,
    setCurrentTheme,
    currentPattern,
    setCurrentPattern,
    taskbarSettings,
    setTaskbarSettings,
    animationSpeed,
    setAnimationSpeed,
    themes,
    patterns,
  } = useContext(ThemeContext);

  const modalVariants = {
    hidden: {
      opacity: 0,
      scale: 0.95,
      y: 20,
    },
    visible: {
      opacity: 1,
      scale: 1,
      y: 0,
      transition: {
        type: "spring",
        duration: 0.5,
        bounce: 0.3,
      },
    },
    exit: {
      opacity: 0,
      scale: 0.95,
      y: 20,
      transition: {
        duration: 0.2,
      },
    },
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="md"
      fullWidth
      TransitionComponent={motion.div}
      TransitionProps={{
        variants: modalVariants,
        initial: "hidden",
        animate: "visible",
        exit: "exit",
      }}
    >
      <DialogTitle>Desktop Settings</DialogTitle>
      <Box sx={{ borderBottom: 1, borderColor: "divider" }}>
        <Tabs value={tab} onChange={(e, newValue) => setTab(newValue)}>
          <Tab label="Theme" />
          <Tab label="Background" />
          <Tab label="Taskbar" />
          <Tab label="Animations" />
        </Tabs>
      </Box>
      <DialogContent>
        <TabPanel value={tab} index={0}>
          <Typography variant="h6" gutterBottom>
            Color Themes
          </Typography>
          <Grid container spacing={2}>
            {Object.entries(themes).map(([key, theme]) => (
              <Grid item xs={6} sm={3} key={key}>
                <Card
                  sx={{
                    position: "relative",
                    border:
                      currentTheme === key
                        ? `2px solid ${theme.colors.primary}`
                        : "none",
                  }}
                >
                  <CardActionArea onClick={() => setCurrentTheme(key)}>
                    <Box
                      sx={{ height: 60, background: theme.colors.primary }}
                    />
                    <CardContent>
                      <Typography variant="subtitle1">{theme.name}</Typography>
                    </CardContent>
                  </CardActionArea>
                </Card>
              </Grid>
            ))}
          </Grid>
        </TabPanel>

        <TabPanel value={tab} index={1}>
          <Typography variant="h6" gutterBottom>
            Background Pattern
          </Typography>
          <Grid container spacing={2}>
            {Object.entries(patterns).map(([key, pattern]) => (
              <Grid item xs={6} sm={3} key={key}>
                <Card
                  sx={{
                    position: "relative",
                    border:
                      currentPattern === key
                        ? `2px solid ${themes[currentTheme].colors.primary}`
                        : "none",
                  }}
                >
                  <CardActionArea onClick={() => setCurrentPattern(key)}>
                    <Box
                      sx={{
                        height: 60,
                        background: pattern.pattern,
                        backgroundColor: themes[currentTheme].colors.background,
                      }}
                    />
                    <CardContent>
                      <Typography variant="subtitle1">
                        {pattern.name}
                      </Typography>
                    </CardContent>
                  </CardActionArea>
                </Card>
              </Grid>
            ))}
          </Grid>
        </TabPanel>

        <TabPanel value={tab} index={2}>
          <Typography variant="h6" gutterBottom>
            Taskbar Settings
          </Typography>
          <Grid container spacing={3}>
            <Grid item xs={12}>
              <FormControlLabel
                control={
                  <Switch
                    checked={taskbarSettings.transparent}
                    onChange={(e) =>
                      setTaskbarSettings((prev) => ({
                        ...prev,
                        transparent: e.target.checked,
                      }))
                    }
                  />
                }
                label="Transparent Taskbar"
              />
            </Grid>
            <Grid item xs={12}>
              <Typography gutterBottom>Taskbar Width</Typography>
              <Slider
                value={taskbarSettings.width}
                onChange={(e, newValue) =>
                  setTaskbarSettings((prev) => ({
                    ...prev,
                    width: newValue,
                  }))
                }
                min={50}
                max={100}
                valueLabelDisplay="auto"
                valueLabelFormat={(value) => `${value}%`}
              />
            </Grid>
            <Grid item xs={12}>
              <Typography gutterBottom>Taskbar Height</Typography>
              <Slider
                value={taskbarSettings.height}
                onChange={(e, newValue) =>
                  setTaskbarSettings((prev) => ({
                    ...prev,
                    height: newValue,
                  }))
                }
                min={40}
                max={80}
                valueLabelDisplay="auto"
                valueLabelFormat={(value) => `${value}px`}
              />
            </Grid>
          </Grid>
        </TabPanel>

        <TabPanel value={tab} index={3}>
          <Typography variant="h6" gutterBottom>
            Animation Settings
          </Typography>
          <Grid container spacing={3}>
            <Grid item xs={12}>
              <Typography gutterBottom>Animation Speed</Typography>
              <Select
                fullWidth
                value={animationSpeed}
                onChange={(e) => setAnimationSpeed(e.target.value)}
              >
                <MenuItem value="slow">Slow</MenuItem>
                <MenuItem value="normal">Normal</MenuItem>
                <MenuItem value="fast">Fast</MenuItem>
              </Select>
            </Grid>
          </Grid>
        </TabPanel>
      </DialogContent>
    </Dialog>
  );
};

// BackgroundPattern Component
export const BackgroundPattern = () => {
  const { currentTheme, currentPattern, themes, patterns } =
    useContext(ThemeContext);

  return (
    <Paper
      elevation={0}
      sx={{
        position: "fixed",
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        borderRadius: 0,
        backgroundColor: themes[currentTheme].colors.background,
        backgroundImage: patterns[currentPattern].pattern,
        backgroundSize: currentPattern === "grid" ? "40px 40px" : "20px 20px",
        zIndex: 5,
      }}
    />
  );
};

// Taskbar Component
export const Taskbar = () => {
  const { windows, activeWindow, focusWindow, createWindow } =
    useWindowManager();
  const [settingsOpen, setSettingsOpen] = useState(false);
  const { currentTheme, taskbarSettings, animationSpeed, themes } =
    useContext(ThemeContext);

  const handleCreateWindow = () => {
    createWindow({
      title: `Window ${Date.now()}`,
      children: (
        <div>
          <h1>New Window</h1>
          <p>This is a new window created programmatically!</p>
        </div>
      ),
      position: {
        x: Math.random() * 200,
        y: Math.random() * 200,
      },
    });
  };

  const getAnimationDuration = (speed) => {
    switch (speed) {
      case "slow":
        return 0.8;
      case "fast":
        return 0.3;
      default:
        return 0.5;
    }
  };

  return (
    <>
      <AnimatePresence>
        <motion.div
          initial={{ y: 100 }}
          animate={{ y: 0 }}
          transition={{
            type: "spring",
            duration: getAnimationDuration(animationSpeed),
            bounce: 0.2,
          }}
          style={{
            position: "fixed",
            bottom: 0,
            left: 0,
            right: 0,
            display: "flex",
            justifyContent: "center",
            zIndex: 9999,
          }}
        >
          <Paper
            elevation={3}
            sx={{
              width: `${taskbarSettings.width}%`,
              height: `${taskbarSettings.height}px`,
              backgroundColor: taskbarSettings.transparent
                ? `rgba(${hexToRgb(themes[currentTheme].colors.taskbar)}, 0.85)`
                : themes[currentTheme].colors.taskbar,
              backdropFilter: "blur(10px)",
              display: "flex",
              alignItems: "center",
              padding: "0 16px",
              gap: "8px",
              borderTopLeftRadius: "20px",
              borderTopRightRadius: "20px",
            }}
          >
            <motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.95 }}>
              <IconButton
                size="small"
                onClick={handleCreateWindow}
                sx={{ color: "white" }}
              >
                <AddIcon />
              </IconButton>
            </motion.div>

            <Box
              sx={{
                flex: 1,
                display: "flex",
                gap: "8px",
                overflowX: "auto",
                py: 1,
              }}
            >
              {Object.entries(windows).map(([id, window]) => (
                <motion.div
                  key={id}
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                >
                  <Button
                    variant={activeWindow === id ? "contained" : "text"}
                    size="small"
                    onClick={() => focusWindow(id)}
                    sx={{
                      color: "white",
                      minWidth: "160px",
                      justifyContent: "flex-start",
                      backgroundColor:
                        activeWindow === id
                          ? "rgba(255, 255, 255, 0.2)"
                          : "transparent",
                      "&:hover": {
                        backgroundColor: "rgba(255, 255, 255, 0.1)",
                      },
                    }}
                  >
                    {window.title}
                  </Button>
                </motion.div>
              ))}
            </Box>

            <motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.95 }}>
              <IconButton
                size="small"
                onClick={() => setSettingsOpen(true)}
                sx={{ color: "white" }}
              >
                <SettingsIcon />
              </IconButton>
            </motion.div>
          </Paper>
        </motion.div>
      </AnimatePresence>

      <SettingsModal
        open={settingsOpen}
        onClose={() => setSettingsOpen(false)}
      />
    </>
  );
};

turn this into multiple files