<template>
  <div>
    <v-toolbar dark>
      <v-spacer />
      <v-toolbar-title>캐릭터 리스트</v-toolbar-title>
      <v-spacer />
    </v-toolbar>

    <br>

    <v-container>
      <v-row align="center">
        <v-col cols="4">
          <v-btn
            color="primary"
            dark
            @click="showAddDialog"
          >
            캐릭터 추가
          </v-btn>
        </v-col>
        <v-col
          cols="8"
          class="d-flex justify-end align-center"
        >
          <v-text-field
            v-model="searchTerm"
            label="검색어"
            placeholder="캐릭터명, 태그, mbti 검색"
            outlined
            dense
            hide-details
            style="max-width: 320px;"
            class="mr-2"
            @keyup.enter="onSearch"
          />
          <v-btn
            :style="{ backgroundColor: '#3bb9f1', color: 'white' }"
            :disabled="is_loading"
            @click="onSearch"
          >
            검색
          </v-btn>
        </v-col>
      </v-row>
      <v-row>
        <v-col>
          <v-simple-table class="elevation-10">
            <template>
              <thead>
                <tr>
                  <th class="text-center">
                    ID
                  </th>
                  <th class="text-center">
                    이미지
                  </th>
                  <th class="text-center">
                    캐릭터명
                  </th>
                  <th class="text-center">
                    성별
                  </th>
                  <th class="text-center">
                    나이
                  </th>
                  <th class="text-center">
                    캐릭터 설명
                  </th>
                  <th class="text-center">
                    MBTI
                  </th>
                  <th class="text-center">
                    말투
                  </th>
                  <th class="text-center">
                    대화 스타일
                  </th>
                  <th class="text-center">
                    태그
                  </th>
                  <th class="text-center">
                    리전
                  </th>
                  <th class="text-center">
                    등록일
                  </th>
                  <th class="text-center">
                    수정일
                  </th>
                  <th class="text-center">
                    관리
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr
                  v-for="item in characters"
                  :key="item.id"
                >
                  <td>{{ item.id }}</td>
                  <td align="center">
                    <v-img
                      max-width="100"
                      max-height="100"
                      :src="item.imageUrl"
                      class="rounded-circle"
                    />
                  </td>
                  <td>{{ item.name }}</td>
                  <td>{{ item.gender || '-' }}</td>
                  <td>{{ item.age || '-' }}</td>
                  <td>
                    <v-btn
                      small
                      color="info"
                      @click="showDetailDialog(item, 'description')"
                    >
                      보기
                    </v-btn>
                  </td>
                  <td>{{ item.mbti || '-' }}</td>
                  <td>
                    <v-btn
                      small
                      color="info"
                      @click="showDetailDialog(item, 'speechPattern')"
                    >
                      보기
                    </v-btn>
                  </td>
                  <td>
                    <v-btn
                      small
                      color="info"
                      @click="showDetailDialog(item, 'speechStyle')"
                    >
                      보기
                    </v-btn>
                  </td>
                  <td>
                    <div v-if="item.tags && item.tags.length > 0">
                      <v-chip
                        v-for="(tag, index) in item.tags"
                        :key="index"
                        small
                        class="ma-1"
                        color="primary"
                        text-color="white"
                      >
                        {{ tag }}
                      </v-chip>
                    </div>
                    <span v-else>-</span>
                  </td>
                  <td>{{ getRegionText(item.region) }}</td>
                  <td>{{ item.createdAt }}</td>
                  <td>{{ item.updatedAt || '-' }}</td>
                  <td>
                    <v-row>
                      <v-col>
                        <v-btn
                          small
                          color="primary"
                          :disabled="is_loading"
                          @click="showEditDialog(item)"
                        >
                          수정
                        </v-btn>
                      </v-col>
                      <v-col>
                        <v-btn
                          small
                          color="info"
                          :disabled="is_loading"
                          @click="goToImageList(item)"
                        >
                          이미지
                        </v-btn>
                      </v-col>
                      <v-col>
                        <v-btn
                          small
                          color="error"
                          :disabled="is_loading"
                          @click="deleteConfirm(item)"
                        >
                          삭제
                        </v-btn>
                      </v-col>
                    </v-row>
                  </td>
                </tr>
              </tbody>
            </template>
          </v-simple-table>
        </v-col>
      </v-row>
      <v-row class="text-center">
        <v-col>
          <v-pagination
            v-model="page"
            :length="total_page"
            circle
            @input="next"
          />
        </v-col>
      </v-row>
    </v-container>


    <!-- 삭제 확인 다이얼로그 -->
    <v-dialog
      v-model="show_delete_confirm_dialog"
      max-width="400px"
      persistent
    >
      <v-card>
        <v-card-text />
        <v-card-text>
          "{{ selected_character.name }}"을(를) 삭제하시겠습니까?
        </v-card-text>
        <v-card-actions v-show="!is_loading">
          <v-spacer />
          <v-btn
            color="blue darken-1"
            text
            @click="closeDeleteDialog"
          >
            취소
          </v-btn>
          <v-btn
            color="red darken-1"
            text
            @click="deleteCharacter"
          >
            확인
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 상세 내용 다이얼로그 -->
    <v-dialog
      v-model="show_detail_dialog"
      max-width="600px"
    >
      <v-card>
        <v-card-title>
          {{ detail_title }}
        </v-card-title>
        <v-divider />
        <v-card-text class="pt-4">
          <div style="white-space: pre-wrap;">
            {{ detail_content }}
          </div>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn
            color="primary"
            text
            @click="closeDetailDialog"
          >
            닫기
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
import { getCharacterList, updateCharacter, searchCharacterList } from '@/api/character'

export default {
  name: "CharacterList",

  data() {
    return {
      is_loading: false,
      show_delete_confirm_dialog: false,
      show_detail_dialog: false,
      detail_type: '',
      detail_content: '',
      detail_title: '',
      page: 1,
      total_page: 0,
      characters: [],
      selected_character: {},
      searchTerm: '',
      regionOptions: [
        { text: '한국', value: 'KR' },
        { text: '일본', value: 'JP' }
      ]
    }
  },

  async created() {
    await this.getCharacters()
  },

  methods: {
    notifyError(message) {
      this.$dialog.notify.error(message)
    },

    notifySuccess(message) {
      this.$dialog.notify.success(message)
    },

    getRegionText(region) {
      if (!region) return '-';
      const option = this.regionOptions.find(opt => opt.value === region);
      return option ? option.text : region;
    },

    showDetailDialog(item, type) {
      this.selected_character = item;
      this.detail_type = type;

      // 타입에 따라 제목과 내용 설정
      switch(type) {
        case 'description':
          this.detail_title = '캐릭터 설명';
          this.detail_content = item.description || '내용이 없습니다.';
          break;
        case 'speechPattern':
          this.detail_title = '말투';
          this.detail_content = item.speechPattern || '내용이 없습니다.';
          break;
        case 'speechStyle':
          this.detail_title = '대화 스타일';
          this.detail_content = item.speechStyle || '내용이 없습니다.';
          break;
        default:
          this.detail_title = '';
          this.detail_content = '';
      }

      this.show_detail_dialog = true;
    },

    closeDetailDialog() {
      this.show_detail_dialog = false;
      this.detail_type = '';
      this.detail_content = '';
      this.detail_title = '';
    },

    showAddDialog() {
      // 페이지로 이동
      this.$router.push('/character/form');
    },

    goToImageList(item) {
      this.$router.push({
        path: '/character/images',
        query: { characterId: item.id, name: item.name }
      })
    },

    showEditDialog(item) {
      // 페이지로 이동하면서 id 전달
      this.$router.push({
        path: '/character/form',
        query: { id: item.id }
      });
    },


    deleteConfirm(item) {
      this.selected_character = item
      this.show_delete_confirm_dialog = true
    },

    closeDeleteDialog() {
      this.show_delete_confirm_dialog = false
      this.selected_character = {}
    },


    async deleteCharacter() {
      if (this.is_loading) return;
      this.is_loading = true

      try {
        // 삭제 대신 isActive를 false로 설정하여 비활성화
        const updateData = {
          id: this.selected_character.id,
          isActive: false
        };
        await updateCharacter(updateData);
        this.closeDeleteDialog();
        this.notifySuccess('삭제되었습니다.');
        await this.getCharacters();
      } catch (e) {
        console.error('캐릭터 삭제 오류:', e);
        this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.');
      } finally {
        this.is_loading = false;
      }
    },

    async next() {
      await this.getCharacters()
    },

    onSearch() {
      this.page = 1;
      this.getCharacters();
    },

    async getCharacters() {
      this.is_loading = true
      try {
        const hasSearch = this.searchTerm && this.searchTerm.trim() !== '';
        const response = hasSearch
          ? await searchCharacterList(this.searchTerm.trim(), this.page, 20)
          : await getCharacterList(this.page);

        if (response && response.status === 200) {
          if (response.data.success === true) {
            const data = response.data.data;
            this.characters = data.content || [];

            const total_page = Math.ceil((data.totalCount || 0) / 20);
            this.total_page = total_page <= 0 ? 1 : total_page;
          } else {
            this.notifyError('응답 데이터가 없습니다.');
          }
        } else {
          this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.');
        }
      } catch (e) {
        console.error('캐릭터 목록 조회 오류:', e);
        this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.');
      } finally {
        this.is_loading = false;
      }
    },

  }
}
</script>

<style scoped>
.v-data-table {
  width: 100%;
}
</style>
