'use client';

import { useEffect, useState, useCallback } from 'react';
import { getMetaTableList, getMetaFields } from '@/lib/api/meta';
import { fcList, fcInsert, fcUpdate } from '@/lib/api/fcData';
import { FcSearch, FcTable, FcForm, FcPagination } from '@/components/fc';
import type { FieldConfig } from '@/types/invyone-component';

export default function TestFcPage() {
  // 테이블 목록
  const [tables, setTables] = useState<Record<string, any>[]>([]);
  const [selectedTable, setSelectedTable] = useState('');

  // FieldConfig
  const [fields, setFields] = useState<FieldConfig[]>([]);
  const [tableLabel, setTableLabel] = useState('');
  const [primaryKey, setPrimaryKey] = useState<string | null>(null);

  // 데이터
  const [data, setData] = useState<Record<string, any>[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [loading, setLoading] = useState(false);

  // 검색 + 행 선택
  const [searchParams, setSearchParams] = useState<Record<string, any>>({});
  const [selectedRow, setSelectedRow] = useState<Record<string, any> | null>(null);
  const [selectedRowIndex, setSelectedRowIndex] = useState<number>(-1);

  // 알림
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  // 1. 테이블 목록 로드
  useEffect(() => {
    getMetaTableList()
      .then(setTables)
      .catch((err) => console.error('테이블 목록 로드 실패:', err));
  }, []);

  // 2. 테이블 선택 시 FieldConfig 로드
  useEffect(() => {
    if (!selectedTable) {
      setFields([]);
      setData([]);
      setSelectedRow(null);
      return;
    }

    getMetaFields(selectedTable)
      .then((meta) => {
        setFields(meta.fields);
        setTableLabel(meta.table_label);
        setPrimaryKey(meta.primary_key);
        setSearchParams({});
        setSelectedRow(null);
        setSelectedRowIndex(-1);
        setPage(1);
      })
      .catch((err) => console.error('FieldConfig 로드 실패:', err));
  }, [selectedTable]);

  // 3. 데이터 조회 (테이블 선택, 검색, 페이지 변경 시)
  const fetchData = useCallback(async () => {
    if (!selectedTable || fields.length === 0) return;
    setLoading(true);
    try {
      const result = await fcList({
        tableName: selectedTable,
        page,
        size: pageSize,
        ...searchParams,
      });
      setData(result.data);
      setTotal(result.total);
    } catch (err) {
      console.error('데이터 조회 실패:', err);
      setData([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  }, [selectedTable, fields.length, page, pageSize, searchParams]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  // 4. 검색 연동: FcSearch → FcTable
  const handleSearch = useCallback((params: Record<string, any>) => {
    setSearchParams(params);
    setPage(1);
    setSelectedRow(null);
    setSelectedRowIndex(-1);
  }, []);

  // 5. 행 선택 연동: FcTable → FcForm
  const handleRowSelect = useCallback((row: Record<string, any>) => {
    setSelectedRow(row);
    const idx = data.findIndex((d) => d === row);
    setSelectedRowIndex(idx);
  }, [data]);

  // 6. 폼 제출: FcForm → DB 저장 → FcTable 새로고침
  const handleFormSubmit = useCallback(async (formData: Record<string, any>) => {
    try {
      if (selectedRow && primaryKey && selectedRow[primaryKey]) {
        // 수정
        await fcUpdate(selectedTable, selectedRow[primaryKey], formData);
        showMessage('success', '수정되었습니다');
      } else {
        // 등록
        await fcInsert(selectedTable, formData);
        showMessage('success', '등록되었습니다');
      }
      fetchData();
    } catch (err: any) {
      showMessage('error', err?.message ?? '저장 실패');
    }
  }, [selectedTable, selectedRow, primaryKey, fetchData]);

  // 페이지 변경
  const handlePageChange = useCallback((params: { page: number; size: number }) => {
    setPage(params.page);
    setPageSize(params.size);
  }, []);

  function showMessage(type: 'success' | 'error', text: string) {
    setMessage({ type, text });
    setTimeout(() => setMessage(null), 3000);
  }

  return (
    <div className="p-4 space-y-3 max-w-[1400px]">
      {/* 헤더 */}
      <div className="flex items-center justify-between">
        <h1 className="text-sm font-bold text-[var(--v5-text)]">
          FieldConfig 컴포넌트 테스트
        </h1>
        {message && (
          <div className={`px-3 py-1 rounded text-xs font-medium
            ${message.type === 'success'
              ? 'bg-[var(--v5-green)]/20 text-[var(--v5-green)]'
              : 'bg-[var(--v5-red)]/20 text-[var(--v5-red)]'}`}
          >
            {message.text}
          </div>
        )}
      </div>

      {/* 테이블 선택 드롭다운 */}
      <div className="flex items-center gap-2">
        <label className="text-xs font-medium text-[var(--v5-text-sec)]">테이블:</label>
        <select
          value={selectedTable}
          onChange={(e) => setSelectedTable(e.target.value)}
          className="h-7 rounded-md border border-[var(--v5-border)] bg-[var(--v5-surface)]
            px-2 text-xs text-[var(--v5-text)] outline-none min-w-[250px]"
        >
          <option value="">테이블 선택...</option>
          {tables.map((t) => (
            <option key={t.table_name} value={t.table_name}>
              {t.table_label !== t.table_name ? `${t.table_label} (${t.table_name})` : t.table_name}
              {t.has_custom_meta ? ' ★' : ''}
            </option>
          ))}
        </select>
        {selectedTable && (
          <span className="text-xs text-[var(--v5-text-muted)]">
            {tableLabel} — {fields.length}개 필드, PK: {primaryKey ?? 'N/A'}
          </span>
        )}
      </div>

      {/* 메인 콘텐츠: 선택된 테이블이 있을 때만 */}
      {selectedTable && fields.length > 0 && (
        <div className="grid grid-cols-[1fr_350px] gap-3">
          {/* 왼쪽: 검색 + 테이블 + 페이지네이션 */}
          <div className="space-y-2">
            <FcSearch
              fields={fields}
              onSearch={handleSearch}
              config={{ layout: 'inline', autoSearch: false }}
            />

            <FcTable
              fields={fields}
              data={data}
              loading={loading}
              onRowSelect={handleRowSelect}
              selectedRowIndex={selectedRowIndex}
              config={{ pageSize, selectionMode: 'single', style: 'compact' }}
            />

            <FcPagination
              total={total}
              page={page}
              pageSize={pageSize}
              onPageChange={handlePageChange}
            />
          </div>

          {/* 오른쪽: 폼 */}
          <div className="space-y-2">
            <div className="text-xs font-medium text-[var(--v5-text-sec)]">
              {selectedRow ? '수정' : '신규 등록'}
            </div>
            <FcForm
              fields={fields}
              loadRow={selectedRow ?? undefined}
              onSubmit={handleFormSubmit}
              config={{ columns: 1, saveAction: { method: selectedRow ? 'UPDATE' : 'INSERT', refreshAfterSave: true } }}
            />
          </div>
        </div>
      )}

      {/* 선택 안 됐을 때 */}
      {!selectedTable && (
        <div className="flex items-center justify-center h-60 rounded-md border border-dashed border-[var(--v5-border)]
          text-[var(--v5-text-muted)] text-xs">
          테이블을 선택하면 FcSearch + FcTable + FcForm이 렌더됩니다
        </div>
      )}
    </div>
  );
}
