import React, { useState } from 'react';
import styled from 'styled-components';
import { HiChatAlt2, HiLockClosed } from 'react-icons/hi';
import { useLocale } from '@/app/providers/LocaleProvider';
import { Button, Card, Textarea } from '@/shared/components/ui';
import { FormActions, FormStack } from '@/shared/components/ui/FormStack';
import { FileUploadZone } from '@/shared/components/ui/FileUpload/FileUploadZone';
import { ImageLightbox } from '@/shared/components/ui/FileUpload/ImageLightbox';

const ComposerWrap = styled.div``;

const NoteSurface = styled.div`
  padding: ${({ theme }) => theme.spacing[4]};
  border-radius: ${({ theme }) => theme.borderRadius.md};
  background: linear-gradient(
    180deg,
    ${({ theme }) => theme.colors.status.warning.bg} 0%,
    ${({ theme }) => theme.colors.surface} 80px
  );
  border: 1px solid ${({ theme }) => theme.colors.status.warning.border};
`;

const TabRow = styled.div`
  display: inline-flex;
  gap: ${({ theme }) => theme.spacing[1]};
  padding: ${({ theme }) => theme.spacing[1]};
  margin-bottom: ${({ theme }) => theme.spacing[4]};
  border-radius: ${({ theme }) => theme.borderRadius.md};
  background: ${({ theme }) => theme.colors.surfaceInset};
  border: 1px solid ${({ theme }) => theme.colors.borderSoft};
`;

const TabButton = styled.button<{ $active: boolean }>`
  display: inline-flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[2]};
  padding: ${({ theme }) => `${theme.spacing[2]} ${theme.spacing[3]}`};
  border: none;
  border-radius: ${({ theme }) => theme.borderRadius.sm};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  font-weight: ${({ theme }) => theme.typography.fontWeight.medium};
  cursor: pointer;
  transition:
    background ${({ theme }) => theme.transitions.fast},
    color ${({ theme }) => theme.transitions.fast};
  background: ${({ $active, theme }) => ($active ? theme.colors.surface : 'transparent')};
  color: ${({ $active, theme }) =>
    $active ? theme.colors.text.primary : theme.colors.text.secondary};
  box-shadow: ${({ $active, theme }) => ($active ? theme.shadows.xs : 'none')};

  svg {
    width: 16px;
    height: 16px;
  }

  &:hover {
    color: ${({ theme }) => theme.colors.text.primary};
  }
`;

const Header = styled.div`
  display: flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[3]};
  margin-bottom: ${({ theme }) => theme.spacing[4]};
`;

const HeaderTitle = styled.h3`
  margin: 0;
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  color: ${({ theme }) => theme.colors.text.primary};
  text-align: start;
`;

const HeaderHint = styled.p`
  margin: ${({ theme }) => theme.spacing[1]} 0 0;
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  color: ${({ theme }) => theme.colors.text.tertiary};
  text-align: start;
  line-height: ${({ theme }) => theme.typography.lineHeight.relaxed};
`;

const UploadSection = styled.div`
  margin-top: ${({ theme }) => theme.spacing[2]};
`;

const ComposerActions = styled(FormActions)<{ $embedded?: boolean }>`
  margin-top: ${({ theme, $embedded }) => ($embedded ? theme.spacing[4] : theme.spacing[5])};
  padding-top: ${({ theme, $embedded }) => ($embedded ? theme.spacing[3] : theme.spacing[5])};
  border-top: ${({ theme, $embedded }) =>
    $embedded ? `1px solid ${theme.colors.borderSoft}` : `1px solid ${theme.colors.divider}`};
`;

const IconBadge = styled.span<{ $tone?: 'warning' }>`
  width: 36px;
  height: 36px;
  border-radius: ${({ theme }) => theme.borderRadius.md};
  display: inline-flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  background-color: ${({ theme, $tone }) =>
    $tone === 'warning' ? theme.colors.status.warning.bg : theme.colors.primaryLight};
  color: ${({ theme, $tone }) =>
    $tone === 'warning' ? theme.colors.status.warning.text : theme.colors.primary};

  svg {
    width: 18px;
    height: 18px;
  }
`;

const EmbeddedHint = styled.p`
  margin: 0 0 ${({ theme }) => theme.spacing[3]};
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  color: ${({ theme }) => theme.colors.text.tertiary};
  text-align: start;
  line-height: ${({ theme }) => theme.typography.lineHeight.relaxed};
`;

export interface ConversationComposerProps {
  variant: 'reply' | 'note';
  value: string;
  onChange: (value: string) => void;
  onSubmit: () => void;
  onCancel?: () => void;
  loading?: boolean;
  files?: File[];
  onFilesChange?: (files: File[]) => void;
  fileError?: string | null;
  showTabs?: boolean;
  showNoteTab?: boolean;
  onVariantChange?: (variant: 'reply' | 'note') => void;
  embedded?: boolean;
}

export const ConversationComposer: React.FC<ConversationComposerProps> = ({
  variant,
  value,
  onChange,
  onSubmit,
  onCancel,
  loading = false,
  files = [],
  onFilesChange,
  fileError,
  showTabs = false,
  showNoteTab = true,
  onVariantChange,
  embedded = false,
}) => {
  const { t } = useLocale();
  const isNote = variant === 'note';
  const [preview, setPreview] = useState<{ src: string; alt: string } | null>(null);
  const canSubmit = Boolean(value.trim() || files.length > 0) && !fileError;

  const body = (
    <>
      {showTabs && onVariantChange && (
        <TabRow role="tablist" aria-label={t('tickets:sections.conversation')}>
          <TabButton
            type="button"
            role="tab"
            aria-selected={!isNote}
            $active={!isNote}
            onClick={() => onVariantChange('reply')}
          >
            <HiChatAlt2 aria-hidden />
            {t('tickets:actions.tabReply')}
          </TabButton>
          {showNoteTab && (
            <TabButton
              type="button"
              role="tab"
              aria-selected={isNote}
              $active={isNote}
              onClick={() => onVariantChange('note')}
            >
              <HiLockClosed aria-hidden />
              {t('tickets:actions.tabNote')}
            </TabButton>
          )}
        </TabRow>
      )}

      {!embedded && (
        <Header>
          <IconBadge $tone={isNote ? 'warning' : undefined} aria-hidden>
            {isNote ? <HiLockClosed /> : <HiChatAlt2 />}
          </IconBadge>
          <div>
            <HeaderTitle>
              {isNote ? t('tickets:actions.addNote') : t('tickets:actions.addReply')}
            </HeaderTitle>
            <HeaderHint>
              {isNote
                ? t('tickets:detail.internalNote')
                : t('tickets:upload.composerHint')}
            </HeaderHint>
          </div>
        </Header>
      )}

      {embedded && (
        <EmbeddedHint>
          {isNote
            ? t('tickets:detail.internalNote')
            : t('tickets:upload.composerHint')}
        </EmbeddedHint>
      )}

      <FormStack>
        <Textarea
          data-testid={isNote ? 'ticket-composer-note' : 'ticket-composer-reply'}
          placeholder={
            isNote ? t('tickets:placeholders.note') : t('tickets:placeholders.reply')
          }
          rows={isNote ? 3 : 4}
          fullWidth
          value={value}
          onChange={(event) => onChange(event.target.value)}
          aria-label={
            isNote ? t('tickets:actions.addNote') : t('tickets:actions.addReply')
          }
        />

        {!isNote && onFilesChange && (
          <UploadSection>
            <FileUploadZone
              files={files}
              onFilesChange={onFilesChange}
              error={fileError}
              disabled={loading}
              onImagePreview={(file, url) =>
                setPreview({ src: url, alt: file.name })
              }
            />
          </UploadSection>
        )}
      </FormStack>

      <ComposerActions $embedded={embedded}>
        <Button
          data-testid="ticket-composer-submit"
          variant={isNote ? 'outline' : 'primary'}
          size="sm"
          loading={loading}
          disabled={!canSubmit}
          onClick={onSubmit}
        >
          {t('common:actions.submit')}
        </Button>
        {onCancel && (
          <Button variant="secondary" size="sm" onClick={onCancel}>
            {t('common:actions.cancel')}
          </Button>
        )}
      </ComposerActions>
    </>
  );

  const wrappedBody = embedded && isNote ? <NoteSurface>{body}</NoteSurface> : body;

  return (
    <ComposerWrap>
      {embedded ? wrappedBody : <Card variant="elevated" padding="lg">{body}</Card>}

      {preview && (
        <ImageLightbox
          src={preview.src}
          alt={preview.alt}
          onClose={() => setPreview(null)}
        />
      )}
    </ComposerWrap>
  );
};
