import {
  ArrowsAltOutlined,
  DeleteOutlined,
  EditOutlined,
  SaveOutlined,
  PlusOutlined,
  ShrinkOutlined,
  UnorderedListOutlined,
} from '@ant-design/icons';
import { Alert, Button, Card, Empty, Form, Input, List, Modal, Segmented, Space, Switch, Tag, Tooltip, Typography } from 'antd';
import { useEffect, useMemo, useRef, useState } from 'react';
import { MarkdownPreviewContent } from '../../components/markdownPreview';
import {
  deleteAutomationType,
  upsertAutomationType,
  useAutomationTypeRegistry,
  type AutomationBehaviorType,
  type AutomationTypeRecord,
} from './automationTypeAccess';
import { confirmWithKeyboard } from './modalKeyboard';
import { useTokenAccess } from './tokenAccess';
import './AutomationTypeManagementPage.css';

const { Text, Title } = Typography;

type AutomationTypeFormValue = {
  id?: string;
  name: string;
  description: string;
  behaviorType: AutomationBehaviorType;
  enabled: boolean;
};

const EMPTY_FORM_VALUE: AutomationTypeFormValue = {
  name: '',
  description: '',
  behaviorType: 'none',
  enabled: true,
};

function toFormValue(automationType: AutomationTypeRecord | null): AutomationTypeFormValue {
  if (!automationType) {
    return EMPTY_FORM_VALUE;
  }

  return {
    id: automationType.id,
    name: automationType.name,
    description: automationType.description,
    behaviorType: automationType.behaviorType,
    enabled: automationType.enabled,
  };
}

export function AutomationTypeManagementPage() {
  const { hasAccess } = useTokenAccess();
  const { automationTypes, setAutomationTypes, isLoading, errorMessage } = useAutomationTypeRegistry();
  const [selectedAutomationTypeId, setSelectedAutomationTypeId] = useState<string | null>(automationTypes[0]?.id ?? null);
  const [isMobileViewport, setIsMobileViewport] = useState(false);
  const [mobileView, setMobileView] = useState<'edit' | 'preview'>('edit');
  const [detailMode, setDetailMode] = useState<'list' | 'detail'>('list');
  const [maximizedPane, setMaximizedPane] = useState<'none' | 'edit' | 'preview'>('none');
  const [isCreating, setIsCreating] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [saveErrorMessage, setSaveErrorMessage] = useState('');
  const [form] = Form.useForm<AutomationTypeFormValue>();
  const [modalApi, modalContextHolder] = Modal.useModal();
  const lastHydratedFormKeyRef = useRef('');
  const isPaneMaximized = maximizedPane !== 'none';

  const selectedAutomationType = useMemo(
    () => automationTypes.find((item) => item.id === selectedAutomationTypeId) ?? null,
    [automationTypes, selectedAutomationTypeId],
  );

  useEffect(() => {
    if (selectedAutomationTypeId && automationTypes.some((item) => item.id === selectedAutomationTypeId)) {
      return;
    }

    setSelectedAutomationTypeId(automationTypes[0]?.id ?? null);
  }, [automationTypes, selectedAutomationTypeId]);

  useEffect(() => {
    if (detailMode !== 'detail') {
      lastHydratedFormKeyRef.current = '';
      return;
    }

    const nextFormKey = isCreating ? '__create__' : selectedAutomationType?.id ?? '__empty__';

    if (lastHydratedFormKeyRef.current === nextFormKey) {
      return;
    }

    lastHydratedFormKeyRef.current = nextFormKey;
    form.resetFields();
    form.setFieldsValue(toFormValue(isCreating ? null : selectedAutomationType));
  }, [detailMode, form, isCreating, selectedAutomationType?.id]);

  useEffect(() => {
    if (detailMode !== 'detail') {
      return;
    }

    if (isCreating || selectedAutomationType) {
      return;
    }

    setDetailMode('list');
  }, [detailMode, isCreating, selectedAutomationType]);

  useEffect(() => {
    if (typeof window === 'undefined') {
      return;
    }

    const mediaQuery = window.matchMedia('(max-width: 960px)');
    const update = () => {
      setIsMobileViewport(mediaQuery.matches);
      if (!mediaQuery.matches) {
        setMobileView('edit');
      }
    };

    update();
    mediaQuery.addEventListener('change', update);

    return () => {
      mediaQuery.removeEventListener('change', update);
    };
  }, []);

  const openCreateForm = () => {
    setIsCreating(true);
    setSelectedAutomationTypeId(null);
    setDetailMode('detail');
    setMaximizedPane('none');
    setMobileView('edit');
    form.resetFields();
    form.setFieldsValue(EMPTY_FORM_VALUE);
  };

  const openDetail = (automationTypeId: string) => {
    setIsCreating(false);
    setSelectedAutomationTypeId(automationTypeId);
    setDetailMode('detail');
    setMaximizedPane('none');
    setMobileView('edit');
  };

  const closeDetail = () => {
    setIsCreating(false);
    setDetailMode('list');
    setMaximizedPane('none');
    setMobileView('edit');
  };

  const handleDelete = async () => {
    if (!selectedAutomationType) {
      return;
    }

    const confirmed = await confirmWithKeyboard(modalApi, {
      title: `"${selectedAutomationType.name}" 자동화 유형을 삭제할까요?`,
      okText: '삭제',
      cancelText: '취소',
      okButtonProps: { danger: true },
    });

    if (!confirmed) {
      return;
    }

    const nextAutomationTypes = deleteAutomationType(automationTypes, selectedAutomationType.id);
    setIsSaving(true);
    setSaveErrorMessage('');

    try {
      const savedAutomationTypes = await setAutomationTypes(nextAutomationTypes);
      setSelectedAutomationTypeId(savedAutomationTypes[0]?.id ?? null);
      setIsCreating(false);
      setDetailMode('list');
      form.resetFields();
      form.setFieldsValue(EMPTY_FORM_VALUE);
    } catch (error) {
      setSaveErrorMessage(error instanceof Error ? error.message : '자동화 처리 유형 삭제에 실패했습니다.');
    } finally {
      setIsSaving(false);
    }
  };

  const detailHeaderActions = (
    <Space size={6} className="chat-type-management-page__header-actions" wrap>
      <Tooltip title={isCreating ? '등록' : '수정 저장'}>
        <Button
          type="primary"
          shape="circle"
          icon={<SaveOutlined />}
          loading={isSaving}
          aria-label={isCreating ? '등록' : '수정 저장'}
          onClick={() => {
            void form.submit();
          }}
        />
      </Tooltip>
      <Tooltip title="새 입력">
        <Button shape="circle" icon={<PlusOutlined />} disabled={isSaving} aria-label="새 입력" onClick={openCreateForm} />
      </Tooltip>
      {!isCreating && selectedAutomationType ? (
        <Tooltip title="삭제">
          <Button
            danger
            shape="circle"
            icon={<DeleteOutlined />}
            loading={isSaving}
            aria-label="삭제"
            onClick={() => void handleDelete()}
          />
        </Tooltip>
      ) : null}
      <Tooltip title="목록 가기">
        <Button shape="circle" icon={<UnorderedListOutlined />} aria-label="목록 가기" onClick={closeDetail} />
      </Tooltip>
    </Space>
  );

  if (!hasAccess) {
    return (
      <>
        {modalContextHolder}
        <Card title="자동화 유형 관리" className="chat-type-management-page">
          <Alert
            showIcon
            type="warning"
            message="관리 페이지는 토큰 등록 사용자만 사용할 수 있습니다."
            description="설정 > 토큰 관리에서 권한 토큰을 등록한 뒤 자동화 처리 유형을 관리하세요."
          />
        </Card>
      </>
    );
  }

  return (
    <div
      className={`chat-type-management-page${detailMode === 'detail' ? ' chat-type-management-page--detail' : ''}${
        isPaneMaximized ? ' chat-type-management-page--pane-maximized' : ''
      }${isMobileViewport ? ` chat-type-management-page--mobile-view-${mobileView}` : ''}`}
    >
      {modalContextHolder}
      {detailMode === 'list' ? (
        <Card
          title="자동화 유형 관리"
          className="chat-type-management-page__card"
          extra={
            <Button icon={<PlusOutlined />} onClick={openCreateForm}>
              신규 유형
            </Button>
          }
        >
          <div className="chat-type-management-page__list">
            {errorMessage ? <Alert showIcon type="error" message={errorMessage} /> : null}
            {saveErrorMessage ? <Alert showIcon type="error" message={saveErrorMessage} /> : null}
            <div className="chat-type-management-page__list-header">
              <Title level={5}>등록 자동화 유형</Title>
              <Text type="secondary">{isLoading ? '불러오는 중' : `${automationTypes.length}건`}</Text>
            </div>

            {automationTypes.length > 0 ? (
              <List
                dataSource={automationTypes}
                renderItem={(item) => {
                  const itemClassName =
                    item.id === selectedAutomationTypeId
                      ? 'chat-type-management-page__item chat-type-management-page__item--active'
                      : 'chat-type-management-page__item';

                  return (
                    <List.Item
                      className={itemClassName}
                      onClick={() => {
                        openDetail(item.id);
                      }}
                      actions={[
                        <Button
                          key="edit"
                          type="text"
                          icon={<EditOutlined />}
                          disabled={isSaving}
                          onClick={(event) => {
                            event.stopPropagation();
                            openDetail(item.id);
                          }}
                        />,
                      ]}
                    >
                      <div className="chat-type-management-page__item-main">
                        <Space size={[8, 8]} wrap>
                          <Text strong>{item.name}</Text>
                          <Tag color={item.enabled ? 'green' : 'default'}>{item.enabled ? '사용' : '중지'}</Tag>
                        </Space>
                        <div className="chat-type-management-page__item-description">
                          {item.description ? <MarkdownPreviewContent content={item.description} maxBlocks={3} /> : '설명 없음'}
                        </div>
                      </div>
                    </List.Item>
                  );
                }}
              />
            ) : (
              <Empty description="등록된 자동화 유형이 없습니다." />
            )}
          </div>
        </Card>
      ) : (
        <Card
          title={isCreating ? '자동화 유형 등록' : '자동화 유형 상세'}
          className={`chat-type-management-page__card${isPaneMaximized ? ' chat-type-management-page__card--pane-maximized' : ''}`}
          extra={detailHeaderActions}
        >
          <div className="chat-type-management-page__editor">
            {errorMessage ? <Alert showIcon type="error" message={errorMessage} /> : null}
            {saveErrorMessage ? <Alert showIcon type="error" message={saveErrorMessage} /> : null}

            <Form
              className="chat-type-management-page__editor-form"
              layout="vertical"
              form={form}
              initialValues={EMPTY_FORM_VALUE}
              onFinish={async (values) => {
                const nextAutomationTypes = upsertAutomationType(automationTypes, {
                  ...values,
                  behaviorType:
                    selectedAutomationType?.behaviorType ?? values.behaviorType ?? EMPTY_FORM_VALUE.behaviorType,
                });
                setIsSaving(true);
                setSaveErrorMessage('');

                try {
                  const savedAutomationTypes = await setAutomationTypes(nextAutomationTypes);
                  const savedAutomationType = savedAutomationTypes.find(
                    (item) => item.id === values.id || item.name === values.name,
                  );
                  setIsCreating(false);
                  setSelectedAutomationTypeId(savedAutomationType?.id ?? null);
                  setDetailMode('detail');
                } catch (error) {
                  setSaveErrorMessage(error instanceof Error ? error.message : '자동화 처리 유형 저장에 실패했습니다.');
                } finally {
                  setIsSaving(false);
                }
              }}
            >
              <Form.Item name="id" hidden>
                <Input />
              </Form.Item>
              <div className="chat-type-management-page__editor-scroll">
                <div className={`chat-type-management-page__meta-grid${isPaneMaximized ? ' chat-type-management-page__meta-grid--hidden' : ''}`}>
                  <Form.Item
                    className="chat-type-management-page__meta-item chat-type-management-page__meta-item--name"
                    label="유형명"
                    name="name"
                    rules={[{ required: true, message: '유형명을 입력하세요.' }]}
                  >
                    <Input placeholder="예: 자동화 메모" />
                  </Form.Item>
                  <Form.Item
                    className="chat-type-management-page__meta-item chat-type-management-page__meta-item--enabled"
                    label="사용 여부"
                    name="enabled"
                    valuePropName="checked"
                  >
                    <Switch checkedChildren="사용" unCheckedChildren="중지" />
                  </Form.Item>
                </div>
                <div className="chat-type-management-page__markdown-field">
                  <Text strong className="chat-type-management-page__field-label">
                    설명
                  </Text>
                  <div className="chat-type-management-page__markdown-editor">
                    <div className="chat-type-management-page__editor-toolbar">
                      {isMobileViewport ? (
                        <Segmented
                          className="chat-type-management-page__mobile-toggle"
                          options={[
                            { label: '입력', value: 'edit' },
                            { label: '미리보기', value: 'preview' },
                          ]}
                          value={mobileView}
                          onChange={(value) => {
                            setMobileView(value as 'edit' | 'preview');
                            setMaximizedPane('none');
                          }}
                        />
                      ) : (
                        <Space size={8} wrap>
                          <Button
                            type={maximizedPane === 'edit' ? 'primary' : 'default'}
                            icon={maximizedPane === 'edit' ? <ShrinkOutlined /> : <ArrowsAltOutlined />}
                            onClick={() => {
                              setMaximizedPane((current) => (current === 'edit' ? 'none' : 'edit'));
                            }}
                          >
                            {maximizedPane === 'edit' ? '입력 축소' : '입력 최대화'}
                          </Button>
                          <Button
                            type={maximizedPane === 'preview' ? 'primary' : 'default'}
                            icon={maximizedPane === 'preview' ? <ShrinkOutlined /> : <ArrowsAltOutlined />}
                            onClick={() => {
                              setMaximizedPane((current) => (current === 'preview' ? 'none' : 'preview'));
                            }}
                          >
                            {maximizedPane === 'preview' ? '미리보기 축소' : '미리보기 최대화'}
                          </Button>
                        </Space>
                      )}
                    </div>
                    <div
                      className={`chat-type-management-page__markdown-grid${
                        maximizedPane !== 'none' ? ' chat-type-management-page__markdown-grid--maximized' : ''
                      }`}
                    >
                      <div
                        className={`chat-type-management-page__markdown-pane${
                          isMobileViewport && mobileView === 'preview'
                            ? ' chat-type-management-page__markdown-pane--mobile-hidden'
                            : ''
                        }${
                          maximizedPane === 'preview' ? ' chat-type-management-page__markdown-pane--desktop-hidden' : ''
                        }`}
                      >
                        <div className="chat-type-management-page__markdown-pane-header">
                          <Text type="secondary">입력</Text>
                          {isMobileViewport ? (
                            <Button
                              size="small"
                              type={maximizedPane === 'edit' ? 'primary' : 'default'}
                              icon={maximizedPane === 'edit' ? <ShrinkOutlined /> : <ArrowsAltOutlined />}
                              onClick={() => {
                                setMaximizedPane((current) => (current === 'edit' ? 'none' : 'edit'));
                              }}
                            >
                              {maximizedPane === 'edit' ? '축소' : '최대화'}
                            </Button>
                          ) : null}
                        </div>
                        <Form.Item name="description" noStyle>
                          <Input.TextArea
                            autoSize={isMobileViewport ? false : { minRows: 12, maxRows: 24 }}
                            className="chat-type-management-page__markdown-textarea"
                            placeholder={
                              '## 처리 기준\n- 이 자동화 유형의 작업 규칙을 Markdown으로 정리하세요.\n\n## 실패 처리\n- 에러/롤백 기준'
                            }
                          />
                        </Form.Item>
                      </div>
                      <div
                        className={`chat-type-management-page__markdown-pane${
                          isMobileViewport && mobileView === 'edit'
                            ? ' chat-type-management-page__markdown-pane--mobile-hidden'
                            : ''
                        }${
                          maximizedPane === 'edit' ? ' chat-type-management-page__markdown-pane--desktop-hidden' : ''
                        }`}
                      >
                        <div className="chat-type-management-page__markdown-preview">
                          <div className="chat-type-management-page__markdown-pane-header">
                            <Text type="secondary">미리보기</Text>
                            {isMobileViewport ? (
                              <Button
                                size="small"
                                type={maximizedPane === 'preview' ? 'primary' : 'default'}
                                icon={maximizedPane === 'preview' ? <ShrinkOutlined /> : <ArrowsAltOutlined />}
                                onClick={() => {
                                  setMaximizedPane((current) => (current === 'preview' ? 'none' : 'preview'));
                                }}
                              >
                                {maximizedPane === 'preview' ? '축소' : '최대화'}
                              </Button>
                            ) : null}
                          </div>
                          <div className="chat-type-management-page__markdown-preview-body">
                            <Form.Item noStyle shouldUpdate={(prev, next) => prev.description !== next.description}>
                              {({ getFieldValue }) => {
                                const description = String(getFieldValue('description') ?? '').trim();

                                return description ? (
                                  <MarkdownPreviewContent content={description} />
                                ) : (
                                  <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="미리보기할 설명이 없습니다." />
                                );
                              }}
                            </Form.Item>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </Form>
          </div>
        </Card>
      )}
    </div>
  );
}
