'use client';
import { FontPicker } from '@/components/typography/FontPicker';
import { SliderWithInput } from '@/src/components/common/SliderWithInput';
import { Button } from '@/components/ui/button';
import { usePortfolioConfig } from '@/src/components/builder/context/PortfolioConfigContext';
import { getInitialValues, setGlobalTypography } from '@/src/lib/typography';
import { TypographyValues } from '@/types/typography';
import { Check } from 'lucide-react';
import { useEffect, useState } from 'react';

type TypographyValueType<K extends keyof TypographyValues> = TypographyValues[K];

export function Typography() {
  const { config, immediateUpdateAndSave } = usePortfolioConfig();
  const [values, setValues] = useState<TypographyValues>(getInitialValues());
  const [pendingChanges, setPendingChanges] = useState<Partial<TypographyValues>>({});
  const [isDirty, setIsDirty] = useState(false);

  useEffect(() => {
    if (config?.typography) {
      setValues(config.typography);
    }
  }, [config]);

  const handleValueChange = <K extends keyof TypographyValues>(key: K, value: TypographyValueType<K>) => {
    setPendingChanges((prev) => ({
      ...prev,
      [key]: value,
    }));
    setIsDirty(true);
  };

  const handleApply = async () => {
    const newValues = {
      ...values,
      ...pendingChanges,
    };

    setValues(newValues);
    setGlobalTypography(newValues);
    setPendingChanges({});
    setIsDirty(false);

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

  const handleReset = () => {
    setPendingChanges({});
    setIsDirty(false);

    setGlobalTypography(values);
  };

  useEffect(() => {
    const currentValues = {
      ...values,
      ...pendingChanges,
    };
    setGlobalTypography(currentValues);
  }, [pendingChanges, values]);

  useEffect(() => {
    if (config?.typography) {
      setValues(config.typography);
      setPendingChanges({});
      setIsDirty(false);
    }
  }, [config]);

  return (
    <div className='flex flex-col h-full w-auto'>
      <div className='flex-1 space-y-8 text-white'>
        <div>
          <h3 className='text-lg font-semibold mb-4'>Heading Typography</h3>
          <div className='space-y-4'>
            <FontPicker
              value={pendingChanges.headingFontFamily ?? values.headingFontFamily}
              onValueChange={(value) => handleValueChange('headingFontFamily', value)}
            />

            <SliderWithInput
              label='Heading Size'
              value={pendingChanges.headingFontSize ?? values.headingFontSize}
              onChange={(value) => handleValueChange('headingFontSize', value ?? 32)}
              min={16}
              max={96}
              step={1}
              unit='px'
            />
          </div>
        </div>

        <div className='border-t border-neutral-600 pt-6'>
          <h3 className='text-lg font-semibold mb-4'>Text Typography</h3>
          <div className='space-y-4'>
            <FontPicker
              value={pendingChanges.textFontFamily ?? values.textFontFamily}
              onValueChange={(value) => handleValueChange('textFontFamily', value)}
            />
          </div>
        </div>
      </div>

      {isDirty && (
        <div className='sticky bottom-0 left-0 bg-neutral-800 mt-6 flex gap-2'>
          <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 Changes
          </Button>
          <Button
            onClick={handleReset}
            className='rounded-sm text-white bg-neutral-700 hover:bg-neutral-600'
            variant='outline'
          >
            Reset
          </Button>
        </div>
      )}
    </div>
  );
}
