import { useState } from 'react';
import { Button, Col, DatePicker, Form, Input, Row, Space, Typography } from 'antd';
import { IconChevronDown, IconChevronUp, IconSearch, IconX } from '@tabler/icons-react';
import dayjs from 'dayjs';
import CodeSelect from './CodeSelect';
import { GRAY, COLOR_PRIMARY } from '@/theme/tokens';

const { Text } = Typography;
const { RangePicker } = DatePicker;

export interface SearchCondition {
  type: 'text' | 'code' | 'dateRange' | 'month';
  name: string;
  label: string;
  groupCode?: string;   // type=code 일 때
  placeholder?: string;
  span?: number;        // 24그리드 기준 너비 (default 6)
}

interface Props {
  conditions: SearchCondition[];
  initialValues?: Record<string, unknown>;
  onSearch: (values: Record<string, unknown>) => void;
  onReset?: () => void;
  /** 초기에 접힘 상태로 시작할지 (default: false = 펼침) */
  defaultCollapsed?: boolean;
}

/**
 * 조건 배열만 넘기면 자동 렌더링되는 검색 폼.
 * - 펼침/접힘 토글 지원
 * - dateRange → startDate/endDate 분해
 * - month → settleMonth (yyyyMM)
 */
export default function SearchForm({
  conditions,
  initialValues,
  onSearch,
  onReset,
  defaultCollapsed = false,
}: Props) {
  const [form]      = Form.useForm();
  const [collapsed, setCollapsed] = useState(defaultCollapsed);

  const handleSearch = (raw: Record<string, unknown>) => {
    const out: Record<string, unknown> = {};
    for (const c of conditions) {
      const v = raw[c.name];
      if (v === undefined || v === null || v === '') continue;
      if (c.type === 'dateRange' && Array.isArray(v) && v.length === 2) {
        out.startDate = (v[0] as dayjs.Dayjs).format('YYYY-MM-DD');
        out.endDate   = (v[1] as dayjs.Dayjs).format('YYYY-MM-DD');
      } else if (c.type === 'month' && v) {
        out[c.name] = (v as dayjs.Dayjs).format('YYYYMM');
      } else {
        out[c.name] = v;
      }
    }
    onSearch(out);
  };

  const handleReset = () => {
    form.resetFields();
    onReset?.();
  };

  return (
    <div
      style={{
        background:   '#ffffff',
        border:       `1px solid ${GRAY[100]}`,
        borderRadius: 16,
        boxShadow:    '0 1px 3px rgba(0,0,0,0.04), 0 4px 16px rgba(0,0,0,0.04)',
        marginBottom: 16,
        overflow:     'hidden',
      }}
    >
      {/* 헤더 — 클릭해서 펼침/접힘 */}
      <div
        onClick={() => setCollapsed(!collapsed)}
        style={{
          display:        'flex',
          alignItems:     'center',
          justifyContent: 'space-between',
          padding:        '10px 16px',
          cursor:         'pointer',
          background:     GRAY[50],
          borderBottom:   collapsed ? 'none' : `1px solid ${GRAY[100]}`,
          userSelect:     'none',
        }}
      >
        <Space size={6} align="center">
          <IconSearch size={14} style={{ color: COLOR_PRIMARY }} />
          <Text style={{ fontSize: 13, fontWeight: 600, color: GRAY[700] }}>검색 조건</Text>
          {collapsed && (
            <Text style={{ fontSize: 12, color: GRAY[400] }}>
              (클릭하여 펼치기)
            </Text>
          )}
        </Space>
        {collapsed
          ? <IconChevronDown size={16} style={{ color: GRAY[400] }} />
          : <IconChevronUp   size={16} style={{ color: GRAY[400] }} />
        }
      </div>

      {/* 폼 본체 */}
      {!collapsed && (
        <Form
          form={form}
          layout="vertical"
          initialValues={initialValues}
          onFinish={handleSearch}
          style={{ padding: '14px 16px 4px' }}
        >
          <Row gutter={[16, 0]}>
            {conditions.map((c) => (
              <Col span={c.span ?? 6} key={c.name}>
                <Form.Item
                  name={c.name}
                  label={
                    <Text style={{ fontSize: 12, fontWeight: 500, color: GRAY[600] }}>
                      {c.label}
                    </Text>
                  }
                  style={{ marginBottom: 14 }}
                >
                  {renderField(c)}
                </Form.Item>
              </Col>
            ))}

            {/* 버튼 컬럼 */}
            <Col span={6} style={{ display: 'flex', alignItems: 'flex-end', paddingBottom: 14 }}>
              <Space>
                <Button
                  type="primary"
                  htmlType="submit"
                  icon={<IconSearch size={14} />}
                  style={{ display: 'flex', alignItems: 'center', gap: 4 }}
                >
                  검색
                </Button>
                <Button
                  onClick={handleReset}
                  icon={<IconX size={14} />}
                  style={{ display: 'flex', alignItems: 'center', gap: 4 }}
                >
                  초기화
                </Button>
              </Space>
            </Col>
          </Row>
        </Form>
      )}
    </div>
  );
}

function renderField(c: SearchCondition) {
  switch (c.type) {
    case 'text':
      return <Input placeholder={c.placeholder} allowClear />;
    case 'code':
      return <CodeSelect groupCode={c.groupCode!} placeholder={c.placeholder} includeAll />;
    case 'dateRange':
      return <RangePicker style={{ width: '100%' }} />;
    case 'month':
      return <DatePicker picker="month" style={{ width: '100%' }} />;
  }
}
