'use client';

import { useState, useEffect, useCallback } from 'react';
import { PageContainer } from '@/components/layout';
import { cn } from '@/utils/helpers';
import apiClient from '@/infrastructure/api/client';
import { API_ENDPOINTS } from '@/infrastructure/api/endpoints';
import { ROLE_TYPE_LABELS } from '@/types/authorization.types';
import type { RoleType } from '@/types/authorization.types';
import styles from './authorization-photos.module.scss';

/** 自助申请照片记录 */
interface SelfApplyPhotoItem {
  id: string;
  accountSequence: string;
  nickname: string;
  avatar: string | null;
  roleType: RoleType;
  regionName: string;
  status: string;
  officePhotoUrls: string[];
  createdAt: string;
}

interface SelfApplyPhotosResponse {
  items: SelfApplyPhotoItem[];
  total: number;
  page: number;
  limit: number;
}

/**
 * 自助申请照片页面
 * [2026-03-02] 纯新增：独立展示所有自助申请用户上传的办公室照片
 * 数据直接读取 authorization-service 源头，不经过 CDC
 */
export default function AuthorizationPhotosPage() {
  const [data, setData] = useState<SelfApplyPhotosResponse | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 筛选
  const [filterType, setFilterType] = useState<RoleType | ''>('');
  const [page, setPage] = useState(1);
  const limit = 20;

  // 照片查看
  const [showPhotoModal, setShowPhotoModal] = useState(false);
  const [selectedItem, setSelectedItem] = useState<SelfApplyPhotoItem | null>(null);
  const [lightboxPhoto, setLightboxPhoto] = useState<string | null>(null);

  const fetchData = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      const params: Record<string, string | number> = { page, limit };
      if (filterType) {
        params.roleType = filterType;
      }
      const response = await apiClient.get(API_ENDPOINTS.AUTHORIZATION.SELF_APPLY_PHOTOS, {
        params,
      });
      // apiClient 响应拦截器已经解包 response.data，这里直接用 response
      setData((response as any) ?? { items: [], total: 0, page: 1, limit: 20 });
    } catch (err) {
      console.error('获取自助申请照片失败:', err);
      setError(err instanceof Error ? err.message : '获取数据失败');
    } finally {
      setIsLoading(false);
    }
  }, [page, limit, filterType]);

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

  const openPhotoModal = (item: SelfApplyPhotoItem) => {
    setSelectedItem(item);
    setShowPhotoModal(true);
  };

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString('zh-CN');
  };

  const totalPages = data ? Math.ceil(data.total / limit) : 0;

  return (
    <PageContainer title="自助申请照片">
      <div className={styles.photos}>
        <section className={styles.photos__card}>
          <div className={styles.photos__cardHeader}>
            <h3 className={styles.photos__cardTitle}>自助申请照片</h3>
            <span className={styles.photos__count}>
              共 {data?.total ?? 0} 条记录
            </span>
          </div>

          {/* 筛选 */}
          <div className={styles.photos__filters}>
            <select
              className={styles.photos__select}
              value={filterType}
              onChange={(e) => {
                setFilterType(e.target.value as RoleType | '');
                setPage(1);
              }}
              aria-label="授权类型"
            >
              <option value="">全部类型</option>
              {Object.entries(ROLE_TYPE_LABELS).map(([value, label]) => (
                <option key={value} value={value}>
                  {label}
                </option>
              ))}
            </select>
          </div>

          {/* 加载状态 */}
          {isLoading && (
            <div className={styles.photos__loading}>加载中...</div>
          )}

          {/* 错误状态 */}
          {error && (
            <div className={styles.photos__error}>
              加载失败: {error}
              <button onClick={fetchData} className={styles.photos__retryBtn}>
                重试
              </button>
            </div>
          )}

          {/* 表格 */}
          {!isLoading && !error && (
            <>
              <div className={styles.photos__table}>
                <div className={styles.photos__tableHeader}>
                  <div className={cn(styles.photos__cell, styles['photos__cell--header'], styles['photos__cell--avatar'])}>
                    头像
                  </div>
                  <div className={cn(styles.photos__cell, styles['photos__cell--header'], styles['photos__cell--nickname'])}>
                    昵称
                  </div>
                  <div className={cn(styles.photos__cell, styles['photos__cell--header'], styles['photos__cell--accountId'])}>
                    账户序列号
                  </div>
                  <div className={cn(styles.photos__cell, styles['photos__cell--header'], styles['photos__cell--type'])}>
                    授权类型
                  </div>
                  <div className={cn(styles.photos__cell, styles['photos__cell--header'], styles['photos__cell--region'])}>
                    地区
                  </div>
                  <div className={cn(styles.photos__cell, styles['photos__cell--header'], styles['photos__cell--photoCount'])}>
                    照片
                  </div>
                  <div className={cn(styles.photos__cell, styles['photos__cell--header'], styles['photos__cell--date'])}>
                    申请时间
                  </div>
                </div>

                {data?.items.map((item) => (
                  <div key={item.id} className={styles.photos__tableRow}>
                    <div className={cn(styles.photos__cell, styles['photos__cell--avatar'])}>
                      <div
                        className={styles.photos__avatar}
                        style={item.avatar ? { backgroundImage: `url(${item.avatar})` } : undefined}
                      />
                    </div>
                    <div className={cn(styles.photos__cell, styles['photos__cell--nickname'])}>
                      {item.nickname || '-'}
                    </div>
                    <div className={cn(styles.photos__cell, styles['photos__cell--accountId'])}>
                      {item.accountSequence}
                    </div>
                    <div className={cn(styles.photos__cell, styles['photos__cell--type'])}>
                      <span className={styles.photos__typeBadge}>
                        {ROLE_TYPE_LABELS[item.roleType] || item.roleType}
                      </span>
                    </div>
                    <div className={cn(styles.photos__cell, styles['photos__cell--region'])}>
                      {item.regionName || '-'}
                    </div>
                    <div className={cn(styles.photos__cell, styles['photos__cell--photoCount'])}>
                      <button
                        className={styles.photos__viewBtn}
                        onClick={() => openPhotoModal(item)}
                      >
                        查看 {item.officePhotoUrls.length} 张
                      </button>
                    </div>
                    <div className={cn(styles.photos__cell, styles['photos__cell--date'])}>
                      {formatDate(item.createdAt)}
                    </div>
                  </div>
                ))}

                {(!data?.items || data.items.length === 0) && (
                  <div className={styles.photos__emptyRow}>暂无自助申请照片记录</div>
                )}
              </div>

              {/* 分页 */}
              {totalPages > 1 && (
                <div className={styles.photos__pagination}>
                  <button
                    className={styles.photos__pageBtn}
                    onClick={() => setPage((p) => Math.max(1, p - 1))}
                    disabled={page <= 1}
                  >
                    上一页
                  </button>
                  <span className={styles.photos__pageInfo}>
                    第 {page} 页 / 共 {totalPages} 页 (共 {data?.total ?? 0} 条)
                  </span>
                  <button
                    className={styles.photos__pageBtn}
                    onClick={() => setPage((p) => p + 1)}
                    disabled={page >= totalPages}
                  >
                    下一页
                  </button>
                </div>
              )}
            </>
          )}

          <p className={styles.photos__help}>
            此页面展示所有通过 App 自助申请授权时上传的办公室照片。仅显示有照片的申请记录。
          </p>
        </section>
      </div>

      {/* 照片查看对话框 */}
      {showPhotoModal && selectedItem && (
        <div className={styles.modal__overlay} onClick={() => setShowPhotoModal(false)}>
          <div
            className={styles.modal__content}
            onClick={(e) => e.stopPropagation()}
          >
            <h3 className={styles.modal__title}>
              {selectedItem.nickname || selectedItem.accountSequence} - 申请照片 ({selectedItem.officePhotoUrls.length} 张)
            </h3>
            <div className={styles.modal__info}>
              <span>账户: {selectedItem.accountSequence}</span>
              <span>类型: {ROLE_TYPE_LABELS[selectedItem.roleType] || selectedItem.roleType}</span>
              <span>地区: {selectedItem.regionName}</span>
            </div>
            <div className={styles.photoGrid}>
              {selectedItem.officePhotoUrls.map((url, index) => (
                <div key={index} className={styles.photoGrid__item}>
                  <img
                    src={url}
                    alt={`申请照片 ${index + 1}`}
                    className={styles.photoGrid__img}
                    onClick={() => setLightboxPhoto(url)}
                  />
                </div>
              ))}
            </div>
            <div className={styles.modal__footer}>
              <button
                className={styles.modal__closeBtn}
                onClick={() => setShowPhotoModal(false)}
              >
                关闭
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 全屏灯箱 */}
      {lightboxPhoto && (
        <div
          className={styles.lightbox}
          onClick={() => setLightboxPhoto(null)}
        >
          <img
            src={lightboxPhoto}
            alt="照片预览"
            className={styles.lightbox__img}
          />
          <span className={styles.lightbox__close}>点击任意处关闭</span>
        </div>
      )}
    </PageContainer>
  );
}
