import {
  ColorContext,
  ColorSelectionType,
  SessionContext,
} from "@/app/context/Context";
import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Tooltip,
  Typography,
  TextField,
  Box,
  FormControlLabel,
  Checkbox,
  Divider,
} from "@mui/material";
import { ColorResult, CompactPicker } from "react-color";
import React, { useState, useContext } from "react";

export const SettingsButton = () => {
  const { colors, setColors } = useContext(ColorContext);
  const { balanceThreshold, setBalanceThreshold, showProductIcons, setShowProductIcons, webhookConfig, setWebhookConfig, webhookServerEnabled } = useContext(SessionContext);
  const [open, setOpen] = useState(false);

  const handleClickOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  const handleColorSelection = (key: string, currentColors: ColorSelectionType) => (selection: ColorResult) => {
    console.log(key, selection.hex)
    setColors({
      ...currentColors,
      [key]: selection.hex
    })
  };

  const handleBalanceThresholdChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const value = parseInt(event.target.value);
    if (!isNaN(value) && value >= 0 && value <= 100000) {
      setBalanceThreshold(value);
    }
  };

  const handleShowProductIconsChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setShowProductIcons(event.target.checked);
  };

  const handleWebhookEnabledChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (!webhookServerEnabled && event.target.checked) {
      // Don't allow enabling if server doesn't support it
      return;
    }
    setWebhookConfig(prev => ({ ...prev, enabled: event.target.checked }));
  };

  const handleExpiryThresholdChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setWebhookConfig(prev => ({ ...prev, expiryThreshold: event.target.value }));
  };

  const handleStorageWarningChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const value = parseInt(event.target.value);
    if (!isNaN(value) && value >= 0 && value <= 100) {
      setWebhookConfig(prev => ({ ...prev, storageWarningThreshold: value }));
    }
  };

  const handleStorageCriticalChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const value = parseInt(event.target.value);
    if (!isNaN(value) && value >= 0 && value <= 100) {
      setWebhookConfig(prev => ({ ...prev, storageCriticalThreshold: value }));
    }
  };

  const handleRefreshStats = () => {
    // Trigger a manual refresh of character data
    window.location.reload();
  };

  const handleRefreshESI = async () => {
    try {
      const response = await fetch("/api/refresh", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ force: true })
      });
      
      if (response.ok) {
        console.log("✅ ESI data refreshed successfully");
        // Optionally reload the page to show fresh data
        window.location.reload();
      } else {
        console.error("❌ Failed to refresh ESI data");
      }
    } catch (error) {
      console.error("❌ Error refreshing ESI data:", error);
    }
  };

  return (
    <Tooltip title="Toggle settings dialog">
      <>
        <Button onClick={handleClickOpen} color="inherit">
          Settings
        </Button>
        <Dialog
          open={open}
          onClose={handleClose}
          aria-labelledby="alert-dialog-title"
          aria-describedby="alert-dialog-description"
        >
          <DialogTitle id="alert-dialog-title">
            {"Settings"}
          </DialogTitle>

          <DialogContent style={{ paddingTop: "1rem" }}>
            <Box sx={{ mt: 2 }}>
              <Typography variant="subtitle1">Display Settings</Typography>
              <FormControlLabel
                control={
                  <Checkbox
                    checked={showProductIcons}
                    onChange={handleShowProductIconsChange}
                  />
                }
                label="Show product icons instead of names"
              />
            </Box>
            <Box sx={{ mt: 2 }}>
              <Typography variant="subtitle1">Balance Threshold</Typography>
              <TextField
                type="number"
                value={balanceThreshold}
                onChange={handleBalanceThresholdChange}
                fullWidth
                margin="normal"
                inputProps={{ min: 0, max: 100000 }}
                helperText="Set the threshold for balance alerts (0-100,000)"
                error={balanceThreshold < 0 || balanceThreshold > 100000}
              />
            </Box>
            
            <Box sx={{ mt: 2 }}>
              <Typography variant="subtitle1">Data Refresh</Typography>
              <Button 
                onClick={handleRefreshESI}
                variant="contained" 
                fullWidth
                sx={{ mt: 1 }}
              >
                Refresh ESI Data
              </Button>
              <Button 
                onClick={handleRefreshStats}
                variant="outlined" 
                fullWidth
                sx={{ mt: 1 }}
              >
                Refresh All Data
              </Button>
            </Box>
            
            <Box sx={{ mt: 3 }}>
              <Divider sx={{ mb: 2 }} />
              <Typography variant="subtitle1">Webhook Notifications</Typography>
              <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                Configure Zulip alerts for extractor expiry and storage capacity warnings.
              </Typography>
              
              <FormControlLabel
                control={
                  <Checkbox
                    checked={webhookConfig.enabled}
                    onChange={handleWebhookEnabledChange}
                  />
                }
                label="Enable webhook notifications"
              />

              {webhookConfig.enabled && (
                <>
                  <Typography variant="subtitle2" sx={{ mt: 2, mb: 1 }}>Zulip Configuration</Typography>
                  
                  <TextField
                    label="Zulip URL"
                    value={webhookConfig.zulipUrl || ''}
                    onChange={(e) => setWebhookConfig(prev => ({ ...prev, zulipUrl: e.target.value }))}
                    fullWidth
                    margin="normal"
                    placeholder="https://zulip.site.quack-lab.dev/api/v1/messages"
                    helperText="Zulip API endpoint URL"
                  />
                  
                  <TextField
                    label="Zulip Email"
                    value={webhookConfig.zulipEmail || ''}
                    onChange={(e) => setWebhookConfig(prev => ({ ...prev, zulipEmail: e.target.value }))}
                    fullWidth
                    margin="normal"
                    placeholder="evepi-bot@zulip.site.quack-lab.dev"
                    helperText="Bot email for authentication"
                  />
                  
                  <TextField
                    label="Zulip API Key"
                    type="password"
                    value={webhookConfig.zulipApiKey || ''}
                    onChange={(e) => setWebhookConfig(prev => ({ ...prev, zulipApiKey: e.target.value }))}
                    fullWidth
                    margin="normal"
                    placeholder="9LlHp6flAGWF0x5KZnyMJTM3qm4CiHkn"
                    helperText="API key for authentication"
                  />
                  
                  <TextField
                    label="Zulip Stream"
                    value={webhookConfig.zulipStream || ''}
                    onChange={(e) => setWebhookConfig(prev => ({ ...prev, zulipStream: e.target.value }))}
                    fullWidth
                    margin="normal"
                    placeholder="EvePI"
                    helperText="Stream name for messages"
                  />

                  <Typography variant="subtitle2" sx={{ mt: 3, mb: 1 }}>Alert Thresholds</Typography>
                  
                  <TextField
                    label="Extractor Expiry Warning"
                    value={webhookConfig.expiryThreshold}
                    onChange={handleExpiryThresholdChange}
                    fullWidth
                    margin="normal"
                    helperText="ISO 8601 duration format (e.g., P12H for 12 hours, P1D for 1 day)"
                  />
                  
                  <TextField
                    type="number"
                    label="Storage Warning Threshold (%)"
                    value={webhookConfig.storageWarningThreshold}
                    onChange={handleStorageWarningChange}
                    fullWidth
                    margin="normal"
                    inputProps={{ min: 0, max: 100 }}
                    helperText="Alert when storage reaches this percentage (0-100)"
                  />
                  
                   <TextField
                     type="number"
                     label="Storage Critical Threshold (%)"
                     value={webhookConfig.storageCriticalThreshold}
                     onChange={handleStorageCriticalChange}
                     fullWidth
                     margin="normal"
                     inputProps={{ min: 0, max: 100 }}
                     helperText="Alert when storage is completely full (usually 100)"
                   />
                   
                   <Button 
                     onClick={async () => {
                       try {
                         const response = await fetch("/api/zulip-webhook", {
                           method: "POST",
                           headers: { "Content-Type": "application/json" },
                           body: JSON.stringify({
                             type: 'test',
                             message: 'Test webhook from EvePI',
                             characterName: 'Test Character',
                             planetName: 'Test Planet',
                             timestamp: new Date().toISOString(),
                             zulipUrl: webhookConfig.zulipUrl,
                             zulipEmail: webhookConfig.zulipEmail,
                             zulipApiKey: webhookConfig.zulipApiKey,
                             zulipStream: webhookConfig.zulipStream
                           })
                         });
                         
                         if (response.ok) {
                           alert("✅ Test webhook sent successfully!");
                         } else {
                           const error = await response.text();
                           alert(`❌ Test webhook failed: ${error}`);
                         }
                       } catch (error) {
                         alert(`❌ Error testing webhook: ${error}`);
                       }
                     }} 
                     variant="outlined" 
                     sx={{ mt: 2 }}
                     fullWidth
                   >
                     Test Webhook
                   </Button>
                 </>
               )}
             </Box>

            <Box sx={{ mt: 3 }}>
              <Divider sx={{ mb: 2 }} />
              <Typography variant="subtitle1">Colors</Typography>
            </Box>
            {Object.keys(colors).map((key) => {
              return (
                <div key={`color-row-${key}`}>
                  <Typography>{key}</Typography>
                  <CompactPicker
                    color={colors[key as keyof ColorSelectionType]}
                    onChangeComplete={handleColorSelection(key, colors)}
                  />
                </div>
              );
            })}
          </DialogContent>
          <DialogActions>
            <Button onClick={handleClose}>Close</Button>
          </DialogActions>
        </Dialog>
      </>
    </Tooltip>
  );
};
