import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { EntityPicker } from '@/components/ui/entity-picker';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { revalidateSystemIcon } from '@/lib/revalidate-icon';
import { cn } from '@/lib/utils';
import {
  Setting,
  SettingComponentEnum,
  SettingTypeEnum,
} from '@hed-hog/api-types';
import { useApp } from '@hed-hog/next-app-provider';
import { Eye, EyeOff, Upload } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { useEffect, useRef, useState } from 'react';

type SettingFieldProps = {
  setting: Setting;
  className?: string;
};

export const SettingField = ({ setting, className }: SettingFieldProps) => {
  const t = useTranslations('core.Configurations');
  const { showToastHandler, setSettingValue, request } = useApp();
  const component =
    setting.component?.replaceAll('_', '-') || SettingComponentEnum.INPUT_TEXT;
  const [localValue, setLocalValue] = useState(setting.value);
  const [showSecretValue, setShowSecretValue] = useState(false);
  const debounceTimerRef = useRef<NodeJS.Timeout | undefined>(undefined);
  const isTextInputRef = useRef<boolean>(false);

  const isThemeSetting = (slug: string) => {
    return slug.startsWith('theme-') || slug === 'menu-width';
  };

  const applyThemeSettings = async () => {
    try {
      const response: any = await request({
        url: '/setting/initial',
        method: 'GET',
      });

      const newSettings = response.data?.setting || {};
      localStorage.setItem('settings', JSON.stringify(newSettings));
      window.dispatchEvent(new CustomEvent('hedhog:settings-change'));
    } catch (error) {
      console.error('Error applying theme settings:', error);
    }
  };

  useEffect(() => {
    if (!isTextInputRef.current) return;

    if (debounceTimerRef.current) {
      clearTimeout(debounceTimerRef.current);
    }

    debounceTimerRef.current = setTimeout(() => {
      if (localValue !== setting.value) {
        setSettingValue(setting.slug, localValue)
          .then(async () => {
            showToastHandler('success', t('settingUpdated'));

            if (['icon-url'].includes(setting.slug)) {
              await revalidateSystemIcon();
              showToastHandler('success', t('iconRevalidated'));
              window.location.reload();
            }

            if (isThemeSetting(setting.slug)) {
              await applyThemeSettings();
            }
          })
          .catch(() => {
            showToastHandler('error', t('settingUpdateFailed'));
          });
      }
    }, 500);

    return () => {
      if (debounceTimerRef.current) {
        clearTimeout(debounceTimerRef.current);
      }
    };
  }, [localValue]);

  const handleChangeValue = (newValue: any, immediate = false) => {
    setLocalValue(newValue);
    if (immediate) {
      setSettingValue(setting.slug, newValue)
        .then(async () => {
          showToastHandler('success', t('settingUpdated'));
          if (isThemeSetting(setting.slug)) {
            await applyThemeSettings();
          }
        })
        .catch(() => {
          showToastHandler('error', t('settingUpdateFailed'));
        });
    }
  };

  const getParsedValue = () => {
    const value = localValue;
    if (value === undefined || value === null) return value;

    switch (setting.type) {
      case SettingTypeEnum.NUMBER:
        return typeof value === 'number' ? value : parseFloat(value) || 0;
      case SettingTypeEnum.BOOLEAN:
        return typeof value === 'boolean'
          ? value
          : value === 'true' || value === '1';
      case SettingTypeEnum.ARRAY:
      case SettingTypeEnum.JSON:
        try {
          return typeof value === 'string' ? JSON.parse(value) : value;
        } catch {
          return value;
        }
      default:
        return value;
    }
  };

  const formatValue = (val: any) => {
    switch (setting.type) {
      case SettingTypeEnum.ARRAY:
      case SettingTypeEnum.JSON:
        return typeof val === 'string' ? val : JSON.stringify(val);
      case SettingTypeEnum.BOOLEAN:
        return val ? 'true' : 'false';
      case SettingTypeEnum.NUMBER:
        return val?.toString() || '0';
      default:
        return val;
    }
  };

  const parsedValue = getParsedValue();
  switch (component) {
    case SettingComponentEnum.INPUT_TEXT:
      isTextInputRef.current = true;
      return (
        <Input
          type="text"
          value={parsedValue || ''}
          onChange={(e) => handleChangeValue(formatValue(e.target.value))}
          className={cn(className, 'w-full min-w-0 bg-background md:min-w-50')}
        />
      );

    case SettingComponentEnum.INPUT_NUMBER:
      isTextInputRef.current = true;
      return (
        <Input
          type="number"
          value={parsedValue || 0}
          onChange={(e) =>
            handleChangeValue(formatValue(parseFloat(e.target.value) || 0))
          }
          className={cn(className, 'w-full min-w-0 bg-background md:min-w-50')}
        />
      );

    case SettingComponentEnum.INPUT_SECRET:
      isTextInputRef.current = true;
      return (
        <div className="relative w-full min-w-0 md:min-w-50">
          <Input
            type={showSecretValue ? 'text' : 'password'}
            value={parsedValue || ''}
            onChange={(e) => handleChangeValue(formatValue(e.target.value))}
            className={cn(
              className,
              'w-full min-w-0 bg-background pr-10 md:min-w-50'
            )}
          />
          <Button
            type="button"
            variant="ghost"
            size="icon"
            className="absolute right-1 top-1/2 h-8 w-8 -translate-y-1/2"
            onClick={() => setShowSecretValue((prev) => !prev)}
            aria-label={
              showSecretValue ? t('hidePassword') : t('showPassword')
            }
          >
            {showSecretValue ? (
              <EyeOff className="h-4 w-4" />
            ) : (
              <Eye className="h-4 w-4" />
            )}
          </Button>
        </div>
      );

    case SettingComponentEnum.INPUT_FILE:
      isTextInputRef.current = true;
      const fileInputRef = useRef<HTMLInputElement>(null);
      const [isUploading, setIsUploading] = useState(false);

      const handleFileUpload = async (
        e: React.ChangeEvent<HTMLInputElement>
      ) => {
        const file = e.target.files?.[0];
        if (!file) return;

        setIsUploading(true);
        try {
          const formData = new FormData();
          formData.append('file', file);

          const response: any = await request({
            url: '/file',
            method: 'POST',
            data: formData,
            headers: {
              'Content-Type': 'multipart/form-data',
            },
          });

          const fileId = response.data?.id;

          if (!fileId) {
            throw new Error(t('fileIdNotReturned'));
          }

          const openResponse: any = await request({
            url: `/file/open/${fileId}`,
            method: 'PUT',
          });

          const openUrl = openResponse?.data?.url;

          if (!openUrl) {
            throw new Error(t('temporaryOpenUrlNotReturned'));
          }

          const fileUrl =
            typeof openUrl === 'string' && openUrl.startsWith('http')
              ? openUrl
              : `${String(process.env.NEXT_PUBLIC_API_BASE_URL || '')}${openUrl}`;

          handleChangeValue(formatValue(fileUrl));
          showToastHandler('success', t('fileUploaded'));
        } catch (error) {
          showToastHandler('error', t('fileUploadFailed'));
        } finally {
          setIsUploading(false);
          if (fileInputRef.current) {
            fileInputRef.current.value = '';
          }
        }
      };

      return (
        <div className="flex w-full min-w-0 flex-col gap-2 md:min-w-50">
          {parsedValue && (
            <div>
              <img
                src={parsedValue || ''}
                alt={t('uploadedFileAlt')}
                className="max-w-full md:w-50"
              />
            </div>
          )}
          <div className="flex w-full min-w-0 items-center gap-2">
            <input
              ref={fileInputRef}
              type="file"
              onChange={handleFileUpload}
              className="hidden"
              id={`file-${setting.id}`}
            />
            <Button
              type="button"
              variant="outline"
              size="icon"
              onClick={() => fileInputRef.current?.click()}
              disabled={isUploading}
              className="shrink-0"
            >
              <Upload className="h-4 w-4" />
            </Button>
            <Input
              type="text"
              value={parsedValue || ''}
              onChange={(e) => handleChangeValue(formatValue(e.target.value))}
              className="min-w-0 flex-1 bg-background"
              placeholder={t('fileUrlPlaceholder')}
              disabled={isUploading}
            />
          </div>
        </div>
      );

    case SettingComponentEnum.SWITCH:
      return (
        <Switch
          checked={parsedValue || false}
          onCheckedChange={(checked) =>
            handleChangeValue(formatValue(checked), true)
          }
          className={cn(className)}
        />
      );

    case SettingComponentEnum.CHECKBOX:
      if (setting.type === SettingTypeEnum.ARRAY) {
        const options = setting.setting_list || [];
        const selectedValues: string[] = Array.isArray(parsedValue)
          ? parsedValue
          : [];
        return (
          <div
            className={cn(
              'flex w-full min-w-0 flex-col space-y-2 md:min-w-50',
              className
            )}
          >
            {options.map((option) => (
              <div key={option.id} className="flex items-center space-x-2">
                <Checkbox
                  className="bg-background"
                  checked={selectedValues.includes(option.value)}
                  onCheckedChange={(checked) => {
                    let newValues = [...selectedValues];
                    if (checked) {
                      newValues.push(option.value);
                    } else {
                      newValues = newValues.filter(
                        (val) => val !== option.value
                      );
                    }
                    handleChangeValue(formatValue(newValues), true);
                  }}
                />
                <Label>{option.value}</Label>
              </div>
            ))}
          </div>
        );
      }
      return (
        <Checkbox
          checked={parsedValue || false}
          onCheckedChange={(checked) =>
            handleChangeValue(formatValue(checked), true)
          }
          className={cn(className)}
        />
      );

    case SettingComponentEnum.COMBOBOX:
      const options = setting.setting_list || [];
      return (
        <Select
          value={parsedValue?.toString() || ''}
          onValueChange={(val) => handleChangeValue(formatValue(val), true)}
        >
          <SelectTrigger
            className={cn(
              'w-full min-w-0 bg-background md:min-w-50',
              className
            )}
          >
            <SelectValue placeholder={t('selectOption')} />
          </SelectTrigger>
          <SelectContent>
            {options.map((option) => (
              <SelectItem key={option.id} value={option.value}>
                {option.value}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      );

    case SettingComponentEnum.RADIO:
      const radioOptions = setting.setting_list || [];
      return (
        <RadioGroup
          value={parsedValue?.toString() || ''}
          onValueChange={(val) => handleChangeValue(formatValue(val), true)}
          className={cn(className, 'w-full min-w-0 md:min-w-50')}
        >
          {radioOptions.map((option) => (
            <div key={option.id} className="flex items-center space-x-2">
              <RadioGroupItem
                value={option.value}
                id={`radio-${option.id}`}
                className="bg-background"
              />
              <Label htmlFor={`radio-${option.id}`}>{option.value}</Label>
            </div>
          ))}
        </RadioGroup>
      );

    case SettingComponentEnum.COLOR_PICKER:
      isTextInputRef.current = true;
      return (
        <div className="flex w-full min-w-0 items-center gap-2 md:max-w-50">
          <Input
            type="color"
            value={parsedValue || '#000000'}
            onChange={(e) => handleChangeValue(formatValue(e.target.value))}
            className={cn(
              'h-10 w-10 border-none p-0 cursor-pointer',
              className
            )}
          />
          <Input
            type="text"
            value={parsedValue || '#000000'}
            onChange={(e) => handleChangeValue(formatValue(e.target.value))}
            className="flex-1 bg-background"
            placeholder="#000000"
            maxLength={7}
            minLength={7}
          />
        </div>
      );

    case SettingComponentEnum.ENTITY_PICKER:
      if (setting.slug !== 'mail-profile-id') {
        return (
          <Input
            type="text"
            value={parsedValue || ''}
            onChange={(e) => handleChangeValue(formatValue(e.target.value))}
            className={cn(className, 'bg-background')}
          />
        );
      }
      return (
        <EntityPicker
          placeholder={t('selectMailProfile')}
          value={parsedValue ? Number(parsedValue) : null}
          onChange={(id) =>
            handleChangeValue(id != null ? String(id) : '', true)
          }
          valueType="number"
          loadOptions={async ({ page, pageSize, search }) => {
            const qs = new URLSearchParams({
              page: String(page),
              pageSize: String(pageSize),
            });
            if (search) qs.set('search', search);
            const response: any = await request({
              url: `/mail-profile?${qs}`,
            });
            const paged = response.data;
            return {
              items: paged?.data ?? [],
              hasMore: (paged?.page ?? 0) < (paged?.lastPage ?? 0),
            };
          }}
          getOptionValue={(opt) => opt.id as number}
          getOptionLabel={(opt) => String(opt.name ?? '')}
          getOptionDescription={(opt) => String((opt as any).from_email ?? '')}
          mapSearchToCreateValues={(search) => ({
            name: search,
            provider: 'SMTP',
          })}
          showCreateButton
          onCreate={async (values) => {
            const slug = (values.name || 'profile')
              .toLowerCase()
              .normalize('NFD')
              .replace(/[\u0300-\u036f]/g, '')
              .replace(/[^a-z0-9]+/g, '-')
              .replace(/^-+|-+$/g, '');
            const response: any = await request({
              url: '/mail-profile',
              method: 'POST',
              data: { ...values, slug },
            });
            return response.data;
          }}
          renderCreateContent={({ values, setValue }) => {
            const provider = values.provider || 'SMTP';
            return (
              <div className="space-y-4">
                <div className="space-y-1">
                  <Label>{t('mailProfile.nameLabel')}</Label>
                  <Input
                    value={values.name || ''}
                    onChange={(e) => setValue('name', e.target.value)}
                    placeholder={t('mailProfile.namePlaceholder')}
                  />
                </div>
                <div className="space-y-1">
                  <Label>{t('mailProfile.fromEmailLabel')}</Label>
                  <Input
                    type="email"
                    value={values.from_email || ''}
                    onChange={(e) => setValue('from_email', e.target.value)}
                    placeholder={t('mailProfile.fromEmailPlaceholder')}
                  />
                </div>
                <div className="space-y-1">
                  <Label>{t('mailProfile.providerLabel')}</Label>
                  <Select
                    value={provider}
                    onValueChange={(v) => setValue('provider', v)}
                  >
                    <SelectTrigger className="w-full">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="SMTP">SMTP</SelectItem>
                      <SelectItem value="GMAIL">Gmail</SelectItem>
                      <SelectItem value="SES">
                        {t('mailProfile.providers.ses')}
                      </SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                {provider === 'SMTP' && (
                  <>
                    <div className="space-y-1">
                      <Label>{t('mailProfile.smtpHostLabel')}</Label>
                      <Input
                        value={values.smtp_host || ''}
                        onChange={(e) => setValue('smtp_host', e.target.value)}
                        placeholder={t('mailProfile.smtpHostPlaceholder')}
                      />
                    </div>
                    <div className="space-y-1">
                      <Label>{t('mailProfile.smtpPortLabel')}</Label>
                      <Input
                        type="number"
                        value={values.smtp_port || '587'}
                        onChange={(e) => setValue('smtp_port', e.target.value)}
                        placeholder={t('mailProfile.smtpPortPlaceholder')}
                      />
                    </div>
                    <div className="space-y-1">
                      <Label>{t('mailProfile.smtpUsernameLabel')}</Label>
                      <Input
                        value={values.smtp_username || ''}
                        onChange={(e) =>
                          setValue('smtp_username', e.target.value)
                        }
                        placeholder={t('mailProfile.smtpUsernamePlaceholder')}
                      />
                    </div>
                    <div className="space-y-1">
                      <Label>{t('mailProfile.smtpPasswordLabel')}</Label>
                      <Input
                        type="password"
                        value={values.smtp_password || ''}
                        onChange={(e) =>
                          setValue('smtp_password', e.target.value)
                        }
                      />
                    </div>
                  </>
                )}
                {provider === 'GMAIL' && (
                  <>
                    <div className="space-y-1">
                      <Label>{t('mailProfile.clientIdLabel')}</Label>
                      <Input
                        value={values.gmail_client_id || ''}
                        onChange={(e) =>
                          setValue('gmail_client_id', e.target.value)
                        }
                      />
                    </div>
                    <div className="space-y-1">
                      <Label>{t('mailProfile.clientSecretLabel')}</Label>
                      <Input
                        type="password"
                        value={values.gmail_client_secret || ''}
                        onChange={(e) =>
                          setValue('gmail_client_secret', e.target.value)
                        }
                      />
                    </div>
                    <div className="space-y-1">
                      <Label>{t('mailProfile.refreshTokenLabel')}</Label>
                      <Input
                        value={values.gmail_refresh_token || ''}
                        onChange={(e) =>
                          setValue('gmail_refresh_token', e.target.value)
                        }
                      />
                    </div>
                  </>
                )}
                {provider === 'SES' && (
                  <>
                    <div className="space-y-1">
                      <Label>{t('mailProfile.accessKeyIdLabel')}</Label>
                      <Input
                        value={values.ses_access_key_id || ''}
                        onChange={(e) =>
                          setValue('ses_access_key_id', e.target.value)
                        }
                      />
                    </div>
                    <div className="space-y-1">
                      <Label>{t('mailProfile.secretAccessKeyLabel')}</Label>
                      <Input
                        type="password"
                        value={values.ses_secret_access_key || ''}
                        onChange={(e) =>
                          setValue('ses_secret_access_key', e.target.value)
                        }
                      />
                    </div>
                    <div className="space-y-1">
                      <Label>{t('mailProfile.regionLabel')}</Label>
                      <Input
                        value={values.ses_region || ''}
                        onChange={(e) => setValue('ses_region', e.target.value)}
                        placeholder={t('mailProfile.regionPlaceholder')}
                      />
                    </div>
                  </>
                )}
              </div>
            );
          }}
          className={cn(className, 'w-full min-w-0 md:min-w-50')}
        />
      );

    default:
      return (
        <Input
          type="text"
          value={parsedValue || ''}
          onChange={(e) => handleChangeValue(formatValue(e.target.value))}
          className={cn(className, 'bg-background')}
        />
      );
  }
};
