import { useState, useEffect } from 'react';
import { Plus, Save, Trash2, RefreshCw, FolderOpen, Edit2 } from 'lucide-react';
import { clsx } from 'clsx';
import { comms } from '@/communication';
import { CommonCodeGroup, CommonCode } from '@/types';

export function CommonCodePage() {
  const [groups, setGroups] = useState<CommonCodeGroup[]>([]);
  const [codes, setCodes] = useState<CommonCode[]>([]);
  const [selectedGroup, setSelectedGroup] = useState<string | null>(null);
  const [selectedCode, setSelectedCode] = useState<CommonCode | null>(null);
  const [loading, setLoading] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [editData, setEditData] = useState<Partial<CommonCode>>({});

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

  useEffect(() => {
    if (selectedGroup) {
      loadCodes();
      setSelectedCode(null);
    }
  }, [selectedGroup]);

  const loadGroups = async () => {
    try {
      const result = await comms.getCommonGroups();
      setGroups(result);
    } catch (error) {
      console.error('그룹 로드 실패:', error);
    }
  };

  const loadCodes = async () => {
    if (!selectedGroup) return;
    setLoading(true);
    try {
      const result = await comms.getCommonList(selectedGroup);
      setCodes(result);
    } catch (error) {
      console.error('코드 로드 실패:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    if (!selectedCode) return;
    try {
      const saveData = { ...selectedCode, ...editData } as CommonCode;
      const response = await comms.saveCommon(saveData);
      if (response.Success) {
        setIsEditing(false);
        setEditData({});
        loadCodes();
      } else {
        alert(response.Message || '저장 실패');
      }
    } catch (error) {
      alert('저장 중 오류가 발생했습니다.');
    }
  };

  const handleDelete = async () => {
    if (!selectedCode || selectedCode.idx === 0) return;
    if (!confirm('삭제하시겠습니까?')) return;
    try {
      const response = await comms.deleteCommon(selectedCode.idx);
      if (response.Success) {
        setSelectedCode(null);
        setIsEditing(false);
        loadCodes();
      } else {
        alert(response.Message || '삭제 실패');
      }
    } catch (error) {
      alert('삭제 중 오류가 발생했습니다.');
    }
  };

  const handleAddNew = () => {
    if (!selectedGroup) {
      alert('그룹을 먼저 선택하세요.');
      return;
    }
    const newCode: CommonCode = {
      idx: 0,
      grp: selectedGroup,
      code: '',
      svalue: '',
      ivalue: 0,
      fvalue: 0,
      memo: '',
    };
    setSelectedCode(newCode);
    setEditData(newCode);
    setIsEditing(true);
  };

  const handleCancel = () => {
    if (selectedCode?.idx === 0) {
      setSelectedCode(null);
    }
    setIsEditing(false);
    setEditData({});
  };

  const selectedGroupName = groups.find((g) => g.code === selectedGroup)?.memo || '';

  return (
    <div className="h-full flex gap-4">
      {/* 좌측: 그룹 목록 */}
      <div className="w-80 flex flex-col gap-4">
        {/* 그룹 목록 */}
        <div className="glass-effect rounded-xl flex-1 overflow-hidden flex flex-col">
          <div className="p-3 border-b border-white/10">
            <h2 className="text-sm font-semibold text-white/70">코드 그룹</h2>
          </div>
          <div className="flex-1 overflow-auto">
            {groups.map((g) => (
              <button
                key={g.code}
                onClick={() => setSelectedGroup(g.code)}
                className={clsx(
                  'w-full px-3 py-2 text-left text-sm flex items-center gap-2 transition-colors',
                  selectedGroup === g.code
                    ? 'bg-blue-600/30 text-white border-l-2 border-blue-500'
                    : 'text-white/70 hover:bg-white/5 hover:text-white'
                )}
              >
                <FolderOpen className="w-4 h-4 flex-shrink-0" />
                <span className="truncate">[{g.code}] {g.memo}</span>
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* 중앙: 코드 목록 */}
      <div className="w-72 flex flex-col">
        <div className="glass-effect rounded-xl flex-1 overflow-hidden flex flex-col">
          <div className="p-3 border-b border-white/10 flex items-center justify-between">
            <div>
              <h2 className="text-sm font-semibold text-white">{selectedGroupName || '그룹 선택'}</h2>
              <p className="text-xs text-white/50">{codes.length}건</p>
            </div>
            <div className="flex items-center gap-1">
              <button
                onClick={loadCodes}
                className="p-1.5 bg-white/10 hover:bg-white/20 rounded text-white/70 hover:text-white transition-colors"
              >
                <RefreshCw className="w-4 h-4" />
              </button>
              <button
                onClick={handleAddNew}
                className="p-1.5 bg-blue-600 hover:bg-blue-700 rounded text-white transition-colors"
              >
                <Plus className="w-4 h-4" />
              </button>
            </div>
          </div>

          <div className="flex-1 overflow-auto">
            {loading ? (
              <div className="flex items-center justify-center h-32">
                <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
              </div>
            ) : selectedGroup ? (
              codes.length > 0 ? (
                codes.map((code) => (
                  <button
                    key={code.idx || 'new'}
                    onClick={() => {
                      setSelectedCode(code);
                      setIsEditing(false);
                      setEditData({});
                    }}
                    className={clsx(
                      'w-full px-3 py-2 text-left border-b border-white/5 transition-colors',
                      selectedCode?.idx === code.idx
                        ? 'bg-blue-600/20 border-l-2 border-l-blue-500'
                        : 'hover:bg-white/5'
                    )}
                  >
                    <div className="text-sm text-white font-medium">{code.code}</div>
                    <div className="text-xs text-white/50 truncate">{code.memo || code.svalue}</div>
                  </button>
                ))
              ) : (
                <div className="p-4 text-center text-white/50 text-sm">
                  데이터가 없습니다.
                </div>
              )
            ) : (
              <div className="p-4 text-center text-white/50 text-sm">
                그룹을 선택하세요.
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 우측: 상세 정보 */}
      <div className="flex-1 glass-effect rounded-xl overflow-hidden flex flex-col">
        <div className="p-4 border-b border-white/10 flex items-center justify-between">
          <h2 className="text-lg font-semibold text-white">
            {selectedCode ? (isEditing ? '코드 편집' : '코드 상세') : '코드 선택'}
          </h2>
          {selectedCode && !isEditing && (
            <div className="flex items-center gap-2">
              <button
                onClick={() => {
                  setIsEditing(true);
                  setEditData(selectedCode);
                }}
                className="flex items-center gap-1 px-3 py-1.5 bg-blue-600 hover:bg-blue-700 rounded text-white text-sm transition-colors"
              >
                <Edit2 className="w-3.5 h-3.5" />
                수정
              </button>
              <button
                onClick={handleDelete}
                className="flex items-center gap-1 px-3 py-1.5 bg-red-600/20 hover:bg-red-600/40 rounded text-red-400 text-sm transition-colors"
              >
                <Trash2 className="w-3.5 h-3.5" />
                삭제
              </button>
            </div>
          )}
        </div>

        <div className="flex-1 overflow-auto p-4">
          {selectedCode ? (
            <div className="space-y-4">
              {/* 코드 */}
              <div>
                <label className="block text-sm font-medium text-white/70 mb-1">코드</label>
                {isEditing ? (
                  <input
                    type="text"
                    value={editData.code ?? selectedCode.code}
                    onChange={(e) => setEditData({ ...editData, code: e.target.value })}
                    className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white"
                  />
                ) : (
                  <div className="px-3 py-2 bg-white/5 rounded-lg text-white">{selectedCode.code}</div>
                )}
              </div>

              {/* 값(S) */}
              <div>
                <label className="block text-sm font-medium text-white/70 mb-1">값 (String)</label>
                {isEditing ? (
                  <input
                    type="text"
                    value={editData.svalue ?? selectedCode.svalue}
                    onChange={(e) => setEditData({ ...editData, svalue: e.target.value })}
                    className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white"
                  />
                ) : (
                  <div className="px-3 py-2 bg-white/5 rounded-lg text-white">{selectedCode.svalue || '-'}</div>
                )}
              </div>

              {/* 값(I) */}
              <div>
                <label className="block text-sm font-medium text-white/70 mb-1">값 (Integer)</label>
                {isEditing ? (
                  <input
                    type="number"
                    value={editData.ivalue ?? selectedCode.ivalue}
                    onChange={(e) => setEditData({ ...editData, ivalue: parseInt(e.target.value) || 0 })}
                    className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white"
                  />
                ) : (
                  <div className="px-3 py-2 bg-white/5 rounded-lg text-white">{selectedCode.ivalue}</div>
                )}
              </div>

              {/* 값(F) */}
              <div>
                <label className="block text-sm font-medium text-white/70 mb-1">값 (Float)</label>
                {isEditing ? (
                  <input
                    type="number"
                    step="0.01"
                    value={editData.fvalue ?? selectedCode.fvalue}
                    onChange={(e) => setEditData({ ...editData, fvalue: parseFloat(e.target.value) || 0 })}
                    className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white"
                  />
                ) : (
                  <div className="px-3 py-2 bg-white/5 rounded-lg text-white">{selectedCode.fvalue}</div>
                )}
              </div>

              {/* 설명 */}
              <div>
                <label className="block text-sm font-medium text-white/70 mb-1">설명</label>
                {isEditing ? (
                  <textarea
                    value={editData.memo ?? selectedCode.memo}
                    onChange={(e) => setEditData({ ...editData, memo: e.target.value })}
                    rows={3}
                    className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white resize-none"
                  />
                ) : (
                  <div className="px-3 py-2 bg-white/5 rounded-lg text-white min-h-[80px]">{selectedCode.memo || '-'}</div>
                )}
              </div>

              {/* 편집 모드 버튼 */}
              {isEditing && (
                <div className="flex items-center gap-2 pt-4">
                  <button
                    onClick={handleSave}
                    className="flex items-center gap-1 px-4 py-2 bg-green-600 hover:bg-green-700 rounded-lg text-white transition-colors"
                  >
                    <Save className="w-4 h-4" />
                    저장
                  </button>
                  <button
                    onClick={handleCancel}
                    className="px-4 py-2 bg-white/10 hover:bg-white/20 rounded-lg text-white/70 hover:text-white transition-colors"
                  >
                    취소
                  </button>
                </div>
              )}
            </div>
          ) : (
            <div className="h-full flex items-center justify-center text-white/50">
              좌측에서 코드를 선택하세요.
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
