import {
  useEffect,
  useState,
} from 'react';

import {
  MoveDown,
  MoveDownLeft,
  MoveDownRight,
  MoveLeft,
  MoveRight,
  MoveUp,
  MoveUpLeft,
  MoveUpRight,
  Plus,
  RotateCw,
  Trash2,
} from 'lucide-react';

import { PaletteCOType } from '@/api/types';
import { toast } from '@/componentsRoot/ToastRoot';
import { Button } from '@/components/ui/button';
import {
  ColorPicker,
  ColorPickerArea,
  ColorPickerContent,
  ColorPickerEyeDropper,
  ColorPickerHueSlider,
  ColorPickerInput,
  ColorPickerSwatch,
  ColorPickerTrigger,
} from '@/components/ui/color-picker';
import { Lang } from '@/lang/Lang';

import DataDescription from './components/DataDescription';
import DataLabel from './components/DataLabel';
import { ItemDataProps } from './types';

// Вычисляет offset для цветов на основе их количества
const calculateOffsets = (count: number): string[] => {
  if (count <= 1) return ['0.00'];
  if (count === 2) return ['0.00', '1.00'];

  const offsets: string[] = [];
  const step = 1 / (count - 1);
  for (let i = 0; i < count; i++) {
    const value = (i * step).toFixed(2);
    offsets.push(value);
  }
  return offsets;
};

export const GradientData = (props: ItemDataProps) => {
  const [localValue, setLocalValue] = useState<{ palette?: PaletteCOType[], angle?: number } | null>(
    props.getValue() ?? null
  );

  useEffect(() => {
    props.setValue(localValue);
  }, [localValue]);

  // Инициализация палитры
  const initialPalette: PaletteCOType[] = localValue?.palette && localValue.palette.length > 0
    ? localValue.palette
    : [
      { color: '#ffffff', offset: '0.00' },
      { color: '#ffffff', offset: '1.00' },
    ];

  const [palette, setPalette] = useState<PaletteCOType[]>(initialPalette);
  const [angle, setAngle] = useState<number>(localValue?.angle ?? 0);
  const [openColorPickerIndex, setOpenColorPickerIndex] = useState<number | null>(null);

  // Синхронизируем localValue при изменении palette или angle
  useEffect(() => {
    setLocalValue({
      palette: palette.length > 0 ? palette : undefined,
      angle: angle,
    });
  }, [palette, angle]);

  const getAngleIcon = (angle: number) => {

    //Находим ближайший угол
    const nearestAngle = angleData.reduce((prev, curr) => {
      return (Math.abs(curr.angle - angle) < Math.abs(prev.angle - angle) ? curr : prev);
    }, angleData[0]);

    return nearestAngle.icon;
  }

  const angleData = [
    {
      angle: 0,
      icon: <MoveUp className="h-4 w-4" />
    },
    {
      angle: 45,
      icon: <MoveUpRight className="h-4 w-4" />
    },
    {
      angle: 90,
      icon: <MoveRight className="h-4 w-4" />
    },
    {
      angle: 135,
      icon: <MoveDownRight className="h-4 w-4" />
    },
    {
      angle: 180,
      icon: <MoveDown className="h-4 w-4" />
    },
    {
      angle: 225,
      icon: <MoveDownLeft className="h-4 w-4" />
    },

    {
      angle: 270,
      icon: <MoveLeft className="h-4 w-4" />
    },
    {
      angle: 315,
      icon: <MoveUpLeft className="h-4 w-4" />
    },
  ];

  // Инициализация из props
  useEffect(() => {
    const value = props.getValue();
    if (value?.palette && value.palette.length > 0) {
      setPalette(value.palette);
    }
    if (value?.angle !== undefined) {
      setAngle(value.angle);
    }
  }, []);

  const addColor = () => {
    const newColor: PaletteCOType = {
      color: '#ffffff',
      offset: '0.00'
    };
    setPalette((prev) => {

      let newPalette = [...prev, newColor];

      newPalette = newPalette.map((item, index) => {
        return {
          ...item,
          offset: (1 / (newPalette.length - 1) * index).toFixed(2),
        };
      });

      return newPalette;


    });
  };

  const removeColor = (index: number) => {




    setPalette((prev) => {




      let newPalette = [...prev];
      newPalette.splice(index, 1);
      newPalette = newPalette.map((item, index) => {
        return {
          ...item,
          offset: (1 / (newPalette.length - 1) * index).toFixed(2),
        };
      });


      if (newPalette.length < 2) {

        toast.error(Lang.key('min_colors_gradient'));
        return prev;
      } else {
        return newPalette;
      }

    });

  };

  const updateColor = (index: number, color: string) => {
    setPalette(prev => prev.map((item, i) =>
      i === index ? { ...item, color } : item
    ));
  };


  // Генерация CSS градиента для превью
  const getGradientCSS = () => {
    if (!palette || palette.length === 0) return '';

    const colors = palette.map(item => {
      let color = item.color || '#ffffff';
      if (item.opacity !== undefined && item.opacity !== 1) {
        // Конвертируем hex в rgba если есть opacity
        if (color.startsWith('#')) {
          const r = parseInt(color.slice(1, 3), 16);
          const g = parseInt(color.slice(3, 5), 16);
          const b = parseInt(color.slice(5, 7), 16);
          color = `rgba(${r}, ${g}, ${b}, ${item.opacity})`;
        }
      }

      let offset = +(item.offset || '0.00') * 100;


      return `${color} ${offset}%`;
    }).join(', ');

    return `linear-gradient(${angle}deg, ${colors})`;
  };

  if (props.onlyShow || !props.structure.editable) {


    return <div>
      <DataLabel {...props} />
      <Button variant="secondary" className='w-full flex items-center justify-between'>
        {palette && palette.length > 0 ? (
          <div
            style={{
              background: getGradientCSS(),
              height: '100px',
              width: '100%',
              borderRadius: '4px',
            }}
          />
        ) : null}
      </Button>
      <DataDescription {...props} />
    </div>


  }

  const nextAngle = () => {

    //Если текущий угол не входит в массив angleData, то устанавливаем угол 0
    if (!angleData.some(item => item.angle === angle)) {
      setAngle(0);
      return;
    }

    let currentAngleIndex = angleData.findIndex(item => item.angle === angle);
    let newAngleIndex = currentAngleIndex + 1;
    if (newAngleIndex >= angleData.length) {
      newAngleIndex = 0;
    }
    let newAngle = angleData[newAngleIndex].angle;

    setAngle(newAngle);
  }

  return (
    <div className="w-full space-y-4">
      <DataLabel {...props} />

      <div
        className='h-10 hover:h-52 transition-all duration-300 mt-2'
        style={{
          background: getGradientCSS(),
          width: '100%',
          borderRadius: '10px',
        }}

      />


      {/* Список цветов */}
      <div className="space-y-2">


        <div className="space-y-2 flex flex-wrap gap-2">


          <Button
            onClick={() => nextAngle()}
            variant="outline" size="sm" className="w-8">
            {getAngleIcon(angle)}
          </Button>


          {palette.map((item, index) => (
            <div
              key={index}
              className="flex items-center gap-2 "
            >

              {/* Цветовой пикер */}
              <ColorPicker
                value={item.color || '#ffffff'}
                onValueChange={(color) => updateColor(index, color)}
                open={openColorPickerIndex === index}
                onOpenChange={(open) => setOpenColorPickerIndex(open ? index : null)}
              >
                <ColorPickerTrigger asChild>
                  <Button variant="outline" size="sm" className="w-32">
                    <ColorPickerSwatch className="size-4 mr-2" />
                    {item.color || '#ffffff'}
                  </Button>
                </ColorPickerTrigger>
                <ColorPickerContent>
                  <ColorPickerArea />
                  <div className="flex items-center gap-2">
                    <ColorPickerEyeDropper />
                    <ColorPickerHueSlider />
                  </div>
                  <ColorPickerInput />
                </ColorPickerContent>
              </ColorPicker>





              {/* Кнопка удаления */}
              <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={() => removeColor(index)}
                disabled={palette.length <= 2}
                className="h-8 w-8 p-0"
              >
                <Trash2 className="h-4 w-4" />
              </Button>
            </div>
          ))}

          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={addColor}
            className="h-8"
          >
            <Plus className="h-4 w-4 mr-1" />
            {Lang.key('add_color')}
          </Button>
        </div>
      </div>

      {/* Кнопка сброса */}
      <Button
        type="button"
        variant="outline"
        onClick={() => {
          setPalette([
            { color: '#ffffff', offset: '0.00' },
            { color: '#000000', offset: '1.00' },
          ]);
          setAngle(0);
        }}
        className="w-full"
      >
        <RotateCw className="h-4 w-4 mr-2" />
        {Lang.key('reset')}
      </Button>

      <DataDescription {...props} />
    </div>
  );
};
