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

// Theme Context
const ThemeContext = createContext();

const themes = {
  blue: {
    name: "Blue",
    colors: {
      primary: "#1976d2",
      secondary: "#1565c0",
      background: "#f0f0f0",
      taskbar: "#2196f3",
      windowHeader: "#1976d2",
    },
  },
  dark: {
    name: "Dark",
    colors: {
      primary: "#424242",
      secondary: "#303030",
      background: "#121212",
      taskbar: "#212121",
      windowHeader: "#424242",
    },
  },
  nature: {
    name: "Nature",
    colors: {
      primary: "#2e7d32",
      secondary: "#1b5e20",
      background: "#e8f5e9",
      taskbar: "#43a047",
      windowHeader: "#2e7d32",
    },
  },
  purple: {
    name: "Purple",
    colors: {
      primary: "#7b1fa2",
      secondary: "#6a1b9a",
      background: "#f3e5f5",
      taskbar: "#9c27b0",
      windowHeader: "#7b1fa2",
    },
  },
};

const patterns = {
  none: {
    name: "None",
    pattern: "",
  },
  dots: {
    name: "Dots",
    pattern: `radial-gradient(rgba(0, 0, 0, 0.1) 1px, transparent 1px),
    radial-gradient(rgba(0, 0, 0, 0.1) 1px, transparent 1px)`,
    backgroundSize: "20px 20px",
    backgroundPosition: "0 0, 10px 10px",
  },
  lines: {
    name: "Lines",
    pattern: `repeating-linear-gradient(
      90deg,
      rgba(0, 0, 0, 0.05) 0px,
      rgba(0, 0, 0, 0.05) 1px,
      transparent 1px,
      transparent 20px
    )`,
  },
  grid: {
    name: "Grid",
    pattern: `linear-gradient(rgba(0, 0, 0, 0.05) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0, 0, 0, 0.05) 1px, transparent 1px),
    linear-gradient(rgba(0, 0, 0, 0.025) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0, 0, 0, 0.025) 1px, transparent 1px)`,
  },
  diamonds: {
    name: "Diamonds",
    pattern: `linear-gradient(45deg, rgba(0, 0, 0, 0.05) 25%, transparent 25%),
    linear-gradient(-45deg, rgba(0, 0, 0, 0.05) 25%, transparent 25%),
    linear-gradient(45deg, transparent 75%, rgba(0, 0, 0, 0.05) 75%),
    linear-gradient(-45deg, transparent 75%, rgba(0, 0, 0, 0.05) 75%)`,
  },
};
const TabPanel = ({ children, value, index, ...other }) => (
  <div role="tabpanel" hidden={value !== index} {...other}>
    {value === index && <Box sx={{ p: 3 }}>{children}</Box>}
  </div>
);
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,
    },
  },
};
const SettingsModal = ({ open, onClose }) => {
  const [tab, setTab] = useState(0);
  const {
    currentTheme,
    setCurrentTheme,
    currentPattern,
    setCurrentPattern,
    taskbarSettings,
    setTaskbarSettings,
    animationSpeed,
    setAnimationSpeed,
  } = useContext(ThemeContext);

  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>
  );
};
const BackgroundPattern = () => {
  const { currentTheme, currentPattern } = 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,
      }}
    />
  );
};
const getAnimationDuration = (speed) => {
  switch (speed) {
    case "slow":
      return 0.8;
    case "fast":
      return 0.3;
    default:
      return 0.5;
  }
};
const Taskbar = () => {
  const { windows, activeWindow, focusWindow } = useWindowManager();
  const [settingsOpen, setSettingsOpen] = useState(false);
  const { currentTheme, taskbarSettings, animationSpeed } =
    useContext(ThemeContext);
  const { createWindow } = useWindowManager();

  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,
      },
    });
  };

  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)}
      />
    </>
  );
};

// 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";
};

const Desktop = () => {
  const [currentTheme, setCurrentTheme] = useState("blue");
  const [currentPattern, setCurrentPattern] = useState("none");
  const [taskbarSettings, setTaskbarSettings] = useState({
    transparent: true,
    width: 80,
    height: 48,
  });
  const [animationSpeed, setAnimationSpeed] = useState("normal");

  const theme = createTheme({
    palette: {
      primary: {
        main: themes[currentTheme].colors.primary,
      },
      secondary: {
        main: themes[currentTheme].colors.secondary,
      },
    },
  });

  return (
    <ThemeProvider theme={theme}>
      <ThemeContext.Provider
        value={{
          currentTheme,
          setCurrentTheme,
          currentPattern,
          setCurrentPattern,
          taskbarSettings,
          setTaskbarSettings,
          animationSpeed,
          setAnimationSpeed,
        }}
      >
        <WindowManagerProvider>
          <div
            style={{
              width: "100vw",
              height: "100vh",
              overflow: "hidden",
              position: "relative",
              backgroundColor: themes[currentTheme].colors.background,
              backgroundImage: patterns[currentPattern].pattern,
              backgroundSize:
                currentPattern === "grid" ? "40px 40px" : "20px 20px",
            }}
          >
            <WindowManager>{/* Windows will be rendered here */}</WindowManager>
            <Taskbar />
          </div>
        </WindowManagerProvider>
      </ThemeContext.Provider>
    </ThemeProvider>
  );
};

export default Desktop;

separate this file into 3 ones