import React, { useContext, useEffect, useState } from 'react';
import styled from 'styled-components';
import Tooltip from '@mui/material/Tooltip';
import InfoOutlined from '@mui/icons-material/InfoOutlined';
import {
  useMaterialUIController,
  setDarkMode,
  setThemeColor,
} from "../../ui-kit/context";
import palettes from "../../ui-kit/assets/theme/base/palettes";
import { AxiosResponse } from "axios";
import { axiosInstance } from "../../../axiosApi";
import { PreferencesType } from "../../data";
import { PreferenceContext } from "../../contexts/PreferencesContext";

// Styled Components (Reusing/Adapting from Account2/Design System)
const GlassCard = styled.div`
  background: ${({ theme }) => theme.colors.cardBackground};
  backdrop-filter: blur(10px);
  border: 1px solid ${({ theme }) => theme.colors.cardBorder};
  border-radius: 1rem;
  padding: 2rem;
  width: 100%;
  max-width: 1000px;
  margin-bottom: 2rem;
  box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.37);
`;

const CardTitle = styled.h2`
  font-size: 1.8rem;
  margin-bottom: 1.5rem;
  color: ${({ theme }) => theme.colors.text};
  border-bottom: 1px solid ${({ theme }) => theme.colors.cardBorder};
  padding-bottom: 1rem;
`;

const SettingRow = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 0;
  border-bottom: 1px solid ${({ theme }) => theme.colors.cardBorder};

  &:last-child {
    border-bottom: none;
  }
`;

const SettingLabel = styled.span`
  font-size: 1.1rem;
  color: ${({ theme }) => theme.colors.text};
  font-weight: 500;
  display: inline-flex;
  align-items: center;
  gap: 0.4rem;
`;

const InfoIcon = styled(InfoOutlined)`
  font-size: 1rem !important;
  opacity: 0.7;
  cursor: help;
  vertical-align: middle;
`;

const ToggleSwitch = styled.label`
  position: relative;
  display: inline-block;
  width: 50px;
  height: 24px;
`;

const Slider = styled.span`
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: ${({ theme }) => theme.darkMode ? 'rgba(255, 255, 255, 0.2)' : 'rgba(0, 0, 0, 0.2)'};
  transition: .4s;
  border-radius: 24px;

  &:before {
    position: absolute;
    content: "";
    height: 16px;
    width: 16px;
    left: 4px;
    bottom: 4px;
    background-color: white;
    transition: .4s;
    border-radius: 50%;
  }
`;

const Checkbox = styled.input`
  opacity: 0;
  width: 0;
  height: 0;

  &:checked + ${Slider} {
    background-color: ${({ theme }) => theme.main};
  }

  &:checked + ${Slider}:before {
    transform: translateX(26px);
  }

  &:disabled + ${Slider} {
    opacity: 0.5;
    cursor: not-allowed;
  }
`;

const ColorPickerContainer = styled.div`
  display: flex;
  gap: 0.5rem;
`;

const ColorButton = styled.button<{ color: string; isSelected: boolean }>`
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: ${(props) => props.color};
  border: 2px solid ${(props) => (props.isSelected ? props.theme.colors.text : 'transparent')};
  cursor: pointer;
  transition: transform 0.2s ease, border-color 0.2s ease;
  box-shadow: 0 2px 5px rgba(0,0,0,0.2);

  &:hover {
    transform: scale(1.1);
  }
`;

const ErrorText = styled.p`
  color: #ff6b6b;
  margin: 0.75rem 0 0 0;
  font-size: 0.95rem;
`;

const CONTEXT_TOOLTIP =
  'This will use previous conversations to better customize the experience.';

function prefsErrorMessage(error: unknown, fallback: string): string {
  const axiosError = error as {
    response?: { data?: { detail?: string } };
    message?: string;
  };
  return axiosError.response?.data?.detail || axiosError.message || fallback;
}

type PreferencesValues = {
  order: boolean;
}

const ThemeSettingsCard = (): JSX.Element => {
  const [controller, dispatch] = useMaterialUIController();
  const {
    darkMode,
    themeColor,
  } = controller;
  const themeColors = Object.keys(palettes);

  const [order, setOrder] = useState<boolean>(true);
  const [useConversationContext, setUseConversationContext] = useState<boolean>(false);
  const [prefsLoading, setPrefsLoading] = useState<boolean>(true);
  const [contextSaving, setContextSaving] = useState<boolean>(false);
  const [prefsError, setPrefsError] = useState<string>('');
  const { updatePreferences } = useContext(PreferenceContext);

  const handleConversationOrder = async ({ order }: PreferencesValues): Promise<void> => {
    try {
      await axiosInstance.post('/conversation_preferences', {
        order: order
      })
      updatePreferences();
    } catch {
      // Error handling
    }
  }

  async function getConversationPreferences() {
    setPrefsLoading(true);
    setPrefsError('');
    try {
      const { data }: AxiosResponse<PreferencesType> = await axiosInstance.get(
        `/conversation_preferences`
      );
      setOrder(data.order);
      setUseConversationContext(Boolean(data.use_conversation_context));
    } catch (error) {
      setPrefsError(
        prefsErrorMessage(error, 'Could not load account preferences.')
      );
    } finally {
      setPrefsLoading(false);
    }
  }

  const handleConversationContext = async (enabled: boolean): Promise<void> => {
    const previous = useConversationContext;
    setUseConversationContext(enabled);
    setContextSaving(true);
    setPrefsError('');
    try {
      const { data }: AxiosResponse<PreferencesType> = await axiosInstance.post(
        '/conversation_preferences',
        { use_conversation_context: enabled }
      );
      setUseConversationContext(Boolean(data.use_conversation_context));
    } catch (error) {
      setUseConversationContext(previous);
      setPrefsError(
        prefsErrorMessage(
          error,
          'Could not update conversation context setting. Try again.'
        )
      );
    } finally {
      setContextSaving(false);
    }
  };

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

  const handleDarkMode = () => setDarkMode(dispatch, !darkMode);

  return (
    <GlassCard>
      <CardTitle>Account Preferences</CardTitle>

      <SettingRow>
        <SettingLabel>Dark Mode</SettingLabel>
        <ToggleSwitch>
          <Checkbox
            type="checkbox"
            checked={darkMode}
            onChange={handleDarkMode}
          />
          <Slider />
        </ToggleSwitch>
      </SettingRow>

      <SettingRow>
        <SettingLabel>Theme Color</SettingLabel>
        <ColorPickerContainer>
          {themeColors.map((color) => (
            <ColorButton
              key={color}
              color={palettes[color as keyof typeof palettes].main}
              isSelected={themeColor === color}
              onClick={() => setThemeColor(dispatch, color)}
              title={color}
            />
          ))}
        </ColorPickerContainer>
      </SettingRow>

      <SettingRow>
        <SettingLabel>Conversation Order (Newest First)</SettingLabel>
        <ToggleSwitch>
          <Checkbox
            type="checkbox"
            checked={order}
            disabled={prefsLoading}
            onChange={() => {
              setOrder(!order);
              handleConversationOrder({ order: !order })
            }}
          />
          <Slider />
        </ToggleSwitch>
      </SettingRow>

      <SettingRow>
        <SettingLabel>
          Use previous conversations
          <Tooltip title={CONTEXT_TOOLTIP}>
            <span>
              <InfoIcon aria-label={CONTEXT_TOOLTIP} />
            </span>
          </Tooltip>
        </SettingLabel>
        <ToggleSwitch>
          <Checkbox
            type="checkbox"
            checked={useConversationContext}
            disabled={prefsLoading || contextSaving}
            onChange={() => {
              handleConversationContext(!useConversationContext);
            }}
          />
          <Slider />
        </ToggleSwitch>
      </SettingRow>

      {prefsError ? <ErrorText role="alert">{prefsError}</ErrorText> : null}

    </GlassCard>
  );
};

export default ThemeSettingsCard;
