import React, { useState } from 'react';
import styled from 'styled-components';
import { useLocale } from '@/app/providers/LocaleProvider';
import { Badge, Button, ColorPicker, Input, Select, Textarea } from '@/shared/components/ui';
import type { SettingItem, SettingScope } from '@/features/settings/types/settings.types';
import { formatSettingValue } from '@/features/settings/types/settings.types';
import { isHexColorKey, normalizeHexColor } from '@/shared/utils/color';

const Row = styled.div`
  display: grid;
  grid-template-columns: 1fr minmax(200px, 280px);
  gap: ${({ theme }) => theme.spacing[4]};
  padding: ${({ theme }) => theme.spacing[4]} 0;
  border-bottom: 1px solid ${({ theme }) => theme.colors.border};
  align-items: start;

  @media (max-width: 768px) {
    grid-template-columns: 1fr;
  }

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

const LabelBlock = styled.div`
  text-align: start;
`;

const Title = styled.div`
  font-weight: ${({ theme }) => theme.typography.fontWeight.medium};
  margin-bottom: ${({ theme }) => theme.spacing[1]};
`;

const Description = styled.div`
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  color: ${({ theme }) => theme.colors.text.secondary};
  margin-bottom: ${({ theme }) => theme.spacing[2]};
`;

const Meta = styled.div`
  display: flex;
  flex-wrap: wrap;
  gap: ${({ theme }) => theme.spacing[2]};
  align-items: center;
`;

const Control = styled.div`
  display: flex;
  flex-direction: column;
  gap: ${({ theme }) => theme.spacing[2]};
`;

const Actions = styled.div`
  display: flex;
  flex-wrap: wrap;
  gap: ${({ theme }) => theme.spacing[2]};
`;

const ErrorText = styled.span`
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  color: ${({ theme }) => theme.colors.error};
`;

interface SettingFieldRowProps {
  setting: SettingItem;
  scope: SettingScope;
  canEdit: boolean;
  isSaving: boolean;
  fieldError?: string | null;
  onSave: (key: string, value: unknown) => void;
  onReset: (key: string) => void;
}

export const SettingFieldRow: React.FC<SettingFieldRowProps> = ({
  setting,
  scope,
  canEdit,
  isSaving,
  fieldError,
  onSave,
  onReset,
}) => {
  const { t } = useLocale();
  const [revealed, setRevealed] = useState(false);
  const [draft, setDraft] = useState<string>(
    formatSettingValue(setting.value, Boolean(setting.is_encrypted), true),
  );

  const sourceLabel = t(`settings:source.${setting.source}`);
  const isColorField = isHexColorKey(setting.key);

  const renderControl = () => {
    if (!canEdit) {
      if (isColorField) {
        return (
          <ColorPicker
            value={normalizeHexColor(setting.value, '#000000')}
            disabled
            fullWidth
          />
        );
      }

      return (
        <Input
          value={formatSettingValue(setting.value, Boolean(setting.is_encrypted), revealed)}
          readOnly
          fullWidth
        />
      );
    }

    if (setting.type === 'boolean') {
      return (
        <Select
          value={String(Boolean(setting.value))}
          onChange={(event) => setDraft(event.target.value)}
          options={[
            { value: 'true', label: t('settings:values.true') },
            { value: 'false', label: t('settings:values.false') },
          ]}
          fullWidth
        />
      );
    }

    if (setting.type === 'json' || setting.type === 'array') {
      return (
        <Textarea
          rows={4}
          value={draft}
          onChange={(event) => setDraft(event.target.value)}
          fullWidth
        />
      );
    }

    if (isColorField) {
      return (
        <ColorPicker
          value={normalizeHexColor(draft, '#000000')}
          onChange={setDraft}
          fullWidth
        />
      );
    }

    return (
      <Input
        type={setting.type === 'number' ? 'number' : 'text'}
        value={setting.is_encrypted && !revealed ? '' : draft}
        placeholder={
          setting.is_encrypted && !revealed
            ? formatSettingValue(setting.value, true, false)
            : undefined
        }
        onChange={(event) => setDraft(event.target.value)}
        fullWidth
      />
    );
  };

  const parseDraftValue = (): unknown => {
    if (setting.type === 'boolean') {
      return draft === 'true';
    }
    if (setting.type === 'number') {
      return Number(draft);
    }
    if (setting.type === 'json' || setting.type === 'array') {
      return JSON.parse(draft);
    }
    return draft;
  };

  return (
    <Row>
      <LabelBlock>
        <Title>{setting.label}</Title>
        {setting.description && <Description>{setting.description}</Description>}
        <Meta>
          <Badge variant="gray" size="sm">
            {sourceLabel}
          </Badge>
          {setting.is_encrypted && (
            <Badge variant="warning" size="sm">
              {t('settings:labels.encrypted')}
            </Badge>
          )}
        </Meta>
      </LabelBlock>

      <Control>
        {renderControl()}
        {setting.is_encrypted && canEdit && (
          <Button type="button" variant="ghost" size="sm" onClick={() => setRevealed((v) => !v)}>
            {revealed ? t('settings:actions.hide') : t('settings:actions.reveal')}
          </Button>
        )}
        {fieldError && <ErrorText role="alert">{fieldError}</ErrorText>}
        {canEdit && (
          <Actions>
            <Button
              type="button"
              variant="primary"
              size="sm"
              loading={isSaving}
              onClick={() => {
                try {
                  onSave(setting.key, parseDraftValue());
                } catch {
                  /* validation handled upstream */
                }
              }}
            >
              {t('common:actions.save')}
            </Button>
            <Button
              type="button"
              variant="outline"
              size="sm"
              loading={isSaving}
              onClick={() => onReset(setting.key)}
            >
              {t('settings:actions.reset')}
            </Button>
          </Actions>
        )}
        <span style={{ fontSize: '12px', color: 'var(--text-secondary)' }}>
          {t('settings:labels.editingScope', { scope: t(`settings:scope.${scope}`) })}
        </span>
      </Control>
    </Row>
  );
};
