'use client';
import { Button } from '@/components/ui/button';
import { colorConfigs } from '@/src/components/builder/config/defaultProps';
import { usePortfolioConfig } from '@/src/components/builder/context/PortfolioConfigContext';
import { setGlobalColors } from '@/lib/theme';
import { Check, Paintbrush, Palette } from 'lucide-react';
import { useEffect, useState } from 'react';
import { ColorResult } from 'react-color';
import rgbHex from 'rgb-hex';
import { ColorPickerButton } from './ColorPickerButton';
import { COLOR_PRESETS } from '@/utils/color';

export function ColorPalletePicker() {
  const { config, immediateUpdateAndSave } = usePortfolioConfig();
  const [isCustomMode, setIsCustomMode] = useState(true);
  const [isDirty, setIsDirty] = useState(false);

  const [colors, setColors] = useState(
    colorConfigs.reduce(
      (acc, config) => ({
        ...acc,
        [config.name]: config.defaultColor,
      }),
      {} as Record<string, string>
    )
  );

  useEffect(() => {
    if (config?.colors) {
      setColors(config.colors);
    }
  }, [config]);

  const handleColorChange = (color: ColorResult, name: string) => {
    const hexColor = `#${rgbHex(color.rgb.r, color.rgb.g, color.rgb.b, color.rgb.a)}`;
    const newColors = {
      ...colors,
      [name]: hexColor,
    };

    setColors(newColors);
    setIsDirty(true);
  };

  const applyPreset = (preset: (typeof COLOR_PRESETS)[0]) => {
    localStorage.setItem('theme', 'light');
    setColors(preset.colors);
    setIsDirty(true);
  };

  const handleApply = async () => {
    setGlobalColors(colors);
    setIsDirty(false);

    try {
      await immediateUpdateAndSave({ colors });
    } catch (error) {
      console.error('Failed to save colors:', error);
    }
  };

  return (
    <div className='space-y-4'>
      <p className='text-sm text-white'>
        Customize your website&apos;s global colors to match your brand. In theme switch mode, text and background
        colors will automatically swap to keep your design looking sharp.
      </p>

      <div className='flex space-x-2 mb-4'>
        <Button
          variant={isCustomMode ? 'default' : 'outline'}
          onClick={() => setIsCustomMode(true)}
          className={isCustomMode ? 'bg-neutral-700' : 'bg-neutral-800'}
        >
          <Paintbrush className='w-6 h-6 mr-2' />
          Custom
        </Button>
        <Button
          variant={!isCustomMode ? 'default' : 'outline'}
          onClick={() => setIsCustomMode(false)}
          className={!isCustomMode ? 'bg-neutral-700' : 'bg-neutral-800'}
        >
          <Palette className='w-6 h-6 mr-2' />
          Presets
        </Button>
      </div>

      {isCustomMode ? (
        <div className='grid gap-3'>
          {colorConfigs.map((config) => (
            <ColorPickerButton
              key={config.name}
              name={config.name}
              label={config.label}
              color={colors[config.name]}
              onColorChange={handleColorChange}
            />
          ))}
        </div>
      ) : (
        <div className='flex flex-col gap-3'>
          {COLOR_PRESETS.map((preset) => {
            const isSelected =
              preset.colors.background === colors.background &&
              preset.colors.text === colors.text &&
              preset.colors.accent === colors.accent;

            return (
              <button
                key={preset.name}
                onClick={() => applyPreset(preset)}
                className={`p-3 flex flex-row justify-between items-center w-full rounded-md cursor-pointer border transition-colors ${
                  isSelected
                    ? 'bg-neutral-700 border-neutral-600'
                    : 'bg-neutral-800 border-neutral-700 hover:bg-neutral-700 hover:border-neutral-600'
                }`}
                aria-label={`Apply ${preset.name} color theme`}
              >
                <div className='text-sm font-medium mb-2'>{preset.name}</div>
                <div className='flex space-x-1'>
                  <div className='w-8 h-8 rounded-full' style={{ backgroundColor: preset.colors.background }} />
                  <div className='w-8 h-8 rounded-full' style={{ backgroundColor: preset.colors.text }} />
                  <div className='w-8 h-8 rounded-full' style={{ backgroundColor: preset.colors.accent }} />
                </div>
              </button>
            );
          })}
        </div>
      )}

      {isDirty && (
        <div className='sticky bottom-0 left-0 bg-neutral-800 border-t border-neutral-600 pt-4'>
          <Button
            onClick={handleApply}
            className='flex-1 rounded-sm text-white bg-neutral-600 hover:bg-neutral-500'
            variant='default'
          >
            <Check className='w-4 h-4 mr-2' />
            Apply Colors
          </Button>
        </div>
      )}
    </div>
  );
}
