'use client';

import { useState, useMemo } from 'react';
import { PageContainer } from '@/components/layout';
import { toast } from '@/components/common';
import { cn } from '@/utils/helpers';
import {
  useAuthorizations,
  useRevokeAuthorization,
  useGrantCommunity,
  useGrantProvinceCompany,
  useGrantCityCompany,
  useGrantAuthProvinceCompany,
  useGrantAuthCityCompany,
} from '@/hooks/useAuthorizations';
import type { RoleType, Authorization } from '@/types/authorization.types';
import { ROLE_TYPE_LABELS } from '@/types/authorization.types';
import styles from './authorization.module.scss';

/**
 * 授权管理页面
 * 使用真实 API 数据
 */
export default function AuthorizationPage() {
  // 筛选状态
  const [filterType, setFilterType] = useState<RoleType | ''>('');
  const [filterStatus, setFilterStatus] = useState<'AUTHORIZED' | 'REVOKED' | ''>('');
  const [searchKeyword, setSearchKeyword] = useState('');
  const [page, setPage] = useState(1);
  const limit = 20;

  // 创建授权对话框状态
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [createForm, setCreateForm] = useState({
    accountSequence: '',
    type: 'COMMUNITY' as RoleType,
    region: '',
    skipAssessment: false,
  });

  // 取消授权对话框状态
  const [showRevokeModal, setShowRevokeModal] = useState(false);
  const [revokeTarget, setRevokeTarget] = useState<Authorization | null>(null);
  const [revokeReason, setRevokeReason] = useState('');

  // 查询参数 - 始终获取所有记录（包括已撤销的），前端做状态筛选
  const queryParams = useMemo(() => ({
    roleType: filterType || undefined,
    keyword: searchKeyword || undefined,
    includeRevoked: true,
    page,
    limit,
  }), [filterType, searchKeyword, page]);

  // 获取授权列表
  const { data, isLoading, error, refetch } = useAuthorizations(queryParams);

  // 撤销授权 mutation
  const revokeMutation = useRevokeAuthorization();

  // 创建授权 mutations
  const grantCommunityMutation = useGrantCommunity();
  const grantProvinceCompanyMutation = useGrantProvinceCompany();
  const grantCityCompanyMutation = useGrantCityCompany();
  const grantAuthProvinceCompanyMutation = useGrantAuthProvinceCompany();
  const grantAuthCityCompanyMutation = useGrantAuthCityCompany();

  // 根据状态筛选数据
  const filteredData = useMemo(() => {
    if (!data?.items) return [];
    if (!filterStatus) return data.items;
    return data.items.filter(item => item.status === filterStatus);
  }, [data?.items, filterStatus]);

  // 从 accountSequence 提取 userId（去掉首字母）
  const extractUserId = (accountSequence: string): string => {
    return accountSequence.slice(1);
  };

  // 判断是否有正在处理的创建请求
  const isCreating =
    grantCommunityMutation.isPending ||
    grantProvinceCompanyMutation.isPending ||
    grantCityCompanyMutation.isPending ||
    grantAuthProvinceCompanyMutation.isPending ||
    grantAuthCityCompanyMutation.isPending;

  // 处理创建授权
  const handleCreate = async () => {
    const { accountSequence, type, region, skipAssessment } = createForm;
    const userId = extractUserId(accountSequence);

    try {
      switch (type) {
        case 'COMMUNITY':
          await grantCommunityMutation.mutateAsync({
            userId,
            accountSequence,
            communityName: region,
            skipAssessment,
          });
          break;
        case 'PROVINCE_COMPANY':
          await grantProvinceCompanyMutation.mutateAsync({
            userId,
            accountSequence,
            provinceCode: region,
            provinceName: region,
            skipAssessment,
          });
          break;
        case 'CITY_COMPANY':
          await grantCityCompanyMutation.mutateAsync({
            userId,
            accountSequence,
            cityCode: region,
            cityName: region,
            skipAssessment,
          });
          break;
        case 'AUTH_PROVINCE_COMPANY':
          await grantAuthProvinceCompanyMutation.mutateAsync({
            userId,
            accountSequence,
            provinceCode: region,
            provinceName: region,
            skipAssessment,
          });
          break;
        case 'AUTH_CITY_COMPANY':
          await grantAuthCityCompanyMutation.mutateAsync({
            userId,
            accountSequence,
            cityCode: region,
            cityName: region,
            skipAssessment,
          });
          break;
      }

      toast.success('授权创建成功');
      setShowCreateModal(false);
      setCreateForm({
        accountSequence: '',
        type: 'COMMUNITY',
        region: '',
        skipAssessment: false,
      });
    } catch (err: unknown) {
      console.error('创建授权失败:', err);
      // 优先从后端响应中获取错误信息
      let errorMessage = '创建授权失败';
      if (err && typeof err === 'object' && 'response' in err) {
        const axiosError = err as { response?: { data?: { message?: string } } };
        errorMessage = axiosError.response?.data?.message || errorMessage;
      } else if (err instanceof Error) {
        errorMessage = err.message;
      }
      toast.error(errorMessage);
    }
  };

  // 处理取消授权
  const handleRevoke = async () => {
    if (!revokeTarget || !revokeReason) return;

    try {
      await revokeMutation.mutateAsync({
        authorizationId: revokeTarget.id,
        data: { reason: revokeReason },
      });
      toast.success('授权已撤销');
      setShowRevokeModal(false);
      setRevokeTarget(null);
      setRevokeReason('');
    } catch (err: unknown) {
      console.error('撤销授权失败:', err);
      let errorMessage = '撤销授权失败';
      if (err && typeof err === 'object' && 'response' in err) {
        const axiosError = err as { response?: { data?: { message?: string } } };
        errorMessage = axiosError.response?.data?.message || errorMessage;
      } else if (err instanceof Error) {
        errorMessage = err.message;
      }
      toast.error(errorMessage);
    }
  };

  // 打开取消授权对话框
  const openRevokeModal = (item: Authorization) => {
    setRevokeTarget(item);
    setShowRevokeModal(true);
  };

  // 判断是否需要地区选择
  const needsRegion = (_type: RoleType) => {
    return true; // 所有类型都需要地区/名称
  };

  // 获取地区输入提示
  const getRegionPlaceholder = (type: RoleType) => {
    switch (type) {
      case 'COMMUNITY':
        return '输入社区名称';
      case 'AUTH_PROVINCE_COMPANY':
      case 'PROVINCE_COMPANY':
        return '选择省份 (如: 广东省)';
      case 'AUTH_CITY_COMPANY':
      case 'CITY_COMPANY':
        return '选择城市 (如: 广东省深圳市)';
      default:
        return '';
    }
  };

  // 渲染开关组件
  const renderToggle = (checked: boolean, onChange: (checked: boolean) => void) => (
    <div
      className={cn(
        styles.authorization__toggle,
        checked ? styles['authorization__toggle--on'] : styles['authorization__toggle--off']
      )}
      onClick={() => onChange(!checked)}
      role="switch"
      aria-checked={checked}
      tabIndex={0}
      onKeyDown={(e) => e.key === 'Enter' && onChange(!checked)}
    >
      <div
        className={cn(
          styles.authorization__toggleHandle,
          checked
            ? styles['authorization__toggleHandle--on']
            : styles['authorization__toggleHandle--off']
        )}
      />
    </div>
  );

  // 格式化日期
  const formatDate = (dateStr: string | null) => {
    if (!dateStr) return '-';
    return new Date(dateStr).toLocaleDateString('zh-CN');
  };

  return (
    <PageContainer title="授权管理">
      <div className={styles.authorization}>
        {/* 授权列表 */}
        <section className={styles.authorization__card}>
          <div className={styles.authorization__cardHeader}>
            <h3 className={styles.authorization__cardTitle}>授权列表</h3>
            <button
              className={styles.authorization__createBtn}
              onClick={() => setShowCreateModal(true)}
            >
              + 创建授权
            </button>
          </div>

          {/* 筛选区域 */}
          <div className={styles.authorization__filters}>
            <select
              className={styles.authorization__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>
            <select
              className={styles.authorization__select}
              value={filterStatus}
              onChange={(e) => {
                setFilterStatus(e.target.value as 'AUTHORIZED' | 'REVOKED' | '');
                setPage(1);
              }}
              aria-label="授权状态"
            >
              <option value="">全部状态</option>
              <option value="AUTHORIZED">有效</option>
              <option value="REVOKED">已撤销</option>
            </select>
            <input
              className={styles.authorization__input}
              placeholder="搜索昵称、账户序列号、地区..."
              type="text"
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && refetch()}
              aria-label="关键词搜索"
            />
            <button
              className={styles.authorization__searchBtn}
              onClick={() => {
                setPage(1);
                refetch();
              }}
            >
              查询
            </button>
          </div>

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

          {/* 错误状态 */}
          {error && (
            <div className={styles.authorization__error}>
              加载失败: {error instanceof Error ? error.message : '未知错误'}
              <button onClick={() => refetch()} className={styles.authorization__retryBtn}>
                重试
              </button>
            </div>
          )}

          {/* 授权表格 */}
          {!isLoading && !error && (
            <>
              <div className={styles.authorization__table}>
                <div className={styles.authorization__tableHeader}>
                  <div
                    className={cn(
                      styles.authorization__tableCell,
                      styles['authorization__tableCell--header'],
                      styles['authorization__tableCell--avatar']
                    )}
                  >
                    头像
                  </div>
                  <div
                    className={cn(
                      styles.authorization__tableCell,
                      styles['authorization__tableCell--header'],
                      styles['authorization__tableCell--nickname']
                    )}
                  >
                    昵称
                  </div>
                  <div
                    className={cn(
                      styles.authorization__tableCell,
                      styles['authorization__tableCell--header'],
                      styles['authorization__tableCell--accountId']
                    )}
                  >
                    账户序列号
                  </div>
                  <div
                    className={cn(
                      styles.authorization__tableCell,
                      styles['authorization__tableCell--header'],
                      styles['authorization__tableCell--type']
                    )}
                  >
                    授权类型
                  </div>
                  <div
                    className={cn(
                      styles.authorization__tableCell,
                      styles['authorization__tableCell--header'],
                      styles['authorization__tableCell--region']
                    )}
                  >
                    地区/名称
                  </div>
                  <div
                    className={cn(
                      styles.authorization__tableCell,
                      styles['authorization__tableCell--header'],
                      styles['authorization__tableCell--date']
                    )}
                  >
                    授权时间
                  </div>
                  <div
                    className={cn(
                      styles.authorization__tableCell,
                      styles['authorization__tableCell--header'],
                      styles['authorization__tableCell--status']
                    )}
                  >
                    状态
                  </div>
                  <div
                    className={cn(
                      styles.authorization__tableCell,
                      styles['authorization__tableCell--header'],
                      styles['authorization__tableCell--actions']
                    )}
                  >
                    操作
                  </div>
                </div>
                {filteredData.map((item) => (
                  <div key={item.id} className={styles.authorization__tableRow}>
                    <div
                      className={cn(
                        styles.authorization__tableCell,
                        styles['authorization__tableCell--avatar']
                      )}
                    >
                      <div
                        className={styles.authorization__avatar}
                        style={item.avatar ? { backgroundImage: `url(${item.avatar})` } : undefined}
                      />
                    </div>
                    <div
                      className={cn(
                        styles.authorization__tableCell,
                        styles['authorization__tableCell--nickname']
                      )}
                    >
                      {item.nickname || '-'}
                    </div>
                    <div
                      className={cn(
                        styles.authorization__tableCell,
                        styles['authorization__tableCell--accountId']
                      )}
                    >
                      {item.accountSequence}
                    </div>
                    <div
                      className={cn(
                        styles.authorization__tableCell,
                        styles['authorization__tableCell--type']
                      )}
                    >
                      <span className={styles.authorization__typeBadge}>
                        {ROLE_TYPE_LABELS[item.roleType] || item.roleType}
                      </span>
                    </div>
                    <div
                      className={cn(
                        styles.authorization__tableCell,
                        styles['authorization__tableCell--region']
                      )}
                    >
                      {item.regionName || '-'}
                    </div>
                    <div
                      className={cn(
                        styles.authorization__tableCell,
                        styles['authorization__tableCell--date']
                      )}
                    >
                      {formatDate(item.authorizedAt || item.createdAt)}
                    </div>
                    <div
                      className={cn(
                        styles.authorization__tableCell,
                        styles['authorization__tableCell--status']
                      )}
                    >
                      <span
                        className={cn(
                          styles.authorization__badge,
                          item.status === 'AUTHORIZED'
                            ? styles['authorization__badge--authorized']
                            : styles['authorization__badge--revoked']
                        )}
                      >
                        {item.status === 'AUTHORIZED' ? '有效' : '已撤销'}
                      </span>
                    </div>
                    <div
                      className={cn(
                        styles.authorization__tableCell,
                        styles['authorization__tableCell--actions']
                      )}
                    >
                      {item.status === 'AUTHORIZED' && (
                        <button
                          className={cn(
                            styles.authorization__actionBtn,
                            styles['authorization__actionBtn--revoke']
                          )}
                          onClick={() => openRevokeModal(item)}
                        >
                          撤销授权
                        </button>
                      )}
                      {item.status === 'REVOKED' && item.revokeReason && (
                        <span className={styles.authorization__revokeReason} title={item.revokeReason}>
                          原因: {item.revokeReason.length > 10 ? `${item.revokeReason.slice(0, 10)}...` : item.revokeReason}
                        </span>
                      )}
                    </div>
                  </div>
                ))}
                {filteredData.length === 0 && (
                  <div className={styles.authorization__emptyRow}>暂无授权记录</div>
                )}
              </div>

              {/* 分页 */}
              {data && data.total > limit && (
                <div className={styles.authorization__pagination}>
                  <button
                    className={styles.authorization__pageBtn}
                    onClick={() => setPage(p => Math.max(1, p - 1))}
                    disabled={page <= 1}
                  >
                    上一页
                  </button>
                  <span className={styles.authorization__pageInfo}>
                    第 {page} 页 / 共 {Math.ceil(data.total / limit)} 页 (共 {data.total} 条)
                  </span>
                  <button
                    className={styles.authorization__pageBtn}
                    onClick={() => setPage(p => p + 1)}
                    disabled={page >= Math.ceil(data.total / limit)}
                  >
                    下一页
                  </button>
                </div>
              )}
            </>
          )}

          <p className={styles.authorization__help}>
            帮助：在此管理所有授权用户，包括社区、省团队、市团队、正式省公司和正式市公司。
          </p>
        </section>
      </div>

      {/* 创建授权对话框 */}
      {showCreateModal && (
        <div className={styles.modal__overlay} onClick={() => setShowCreateModal(false)}>
          <div className={styles.modal__content} onClick={(e) => e.stopPropagation()}>
            <h3 className={styles.modal__title}>创建授权</h3>
            <div className={styles.modal__form}>
              <div className={styles.modal__formGroup}>
                <label className={styles.modal__label}>账户序列号</label>
                <input
                  className={styles.modal__input}
                  type="text"
                  placeholder="输入用户账户序列号 (如: D25122700001)"
                  value={createForm.accountSequence}
                  onChange={(e) =>
                    setCreateForm({ ...createForm, accountSequence: e.target.value })
                  }
                />
              </div>
              <div className={styles.modal__formGroup}>
                <label className={styles.modal__label}>授权类型</label>
                <select
                  className={styles.modal__select}
                  value={createForm.type}
                  onChange={(e) =>
                    setCreateForm({ ...createForm, type: e.target.value as RoleType })
                  }
                >
                  {Object.entries(ROLE_TYPE_LABELS).map(([value, label]) => (
                    <option key={value} value={value}>
                      {label}
                    </option>
                  ))}
                </select>
              </div>
              {needsRegion(createForm.type) && (
                <div className={styles.modal__formGroup}>
                  <label className={styles.modal__label}>
                    {createForm.type === 'COMMUNITY' ? '社区名称' : '地区'}
                  </label>
                  <input
                    className={styles.modal__input}
                    type="text"
                    placeholder={getRegionPlaceholder(createForm.type)}
                    value={createForm.region}
                    onChange={(e) => setCreateForm({ ...createForm, region: e.target.value })}
                  />
                </div>
              )}
              <div className={styles.modal__formGroup}>
                <div className={styles.modal__toggleRow}>
                  <span className={styles.modal__toggleLabel}>跳过考核期</span>
                  {renderToggle(createForm.skipAssessment, (checked) =>
                    setCreateForm({ ...createForm, skipAssessment: checked })
                  )}
                </div>
                <p className={styles.modal__hint}>
                  开启后，用户将直接获得完整权益，无需经过考核期
                </p>
              </div>
            </div>
            <div className={styles.modal__footer}>
              <button
                className={styles.modal__cancelBtn}
                onClick={() => setShowCreateModal(false)}
              >
                取消
              </button>
              <button
                className={styles.modal__confirmBtn}
                onClick={handleCreate}
                disabled={!createForm.accountSequence || !createForm.region || isCreating}
              >
                {isCreating ? '创建中...' : '确认创建'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 撤销授权对话框 */}
      {showRevokeModal && revokeTarget && (
        <div className={styles.modal__overlay} onClick={() => setShowRevokeModal(false)}>
          <div className={styles.modal__content} onClick={(e) => e.stopPropagation()}>
            <h3 className={styles.modal__title}>撤销授权</h3>
            <div className={styles.modal__form}>
              <p className={styles.modal__warning}>
                确定要撤销用户 <strong>{revokeTarget.nickname || revokeTarget.accountSequence}</strong> (
                {revokeTarget.accountSequence}) 的{' '}
                <strong>{ROLE_TYPE_LABELS[revokeTarget.roleType] || revokeTarget.roleType}</strong> 授权吗？
              </p>
              <div className={styles.modal__formGroup}>
                <label className={styles.modal__label}>撤销原因</label>
                <textarea
                  className={styles.modal__textarea}
                  placeholder="请输入撤销原因..."
                  value={revokeReason}
                  onChange={(e) => setRevokeReason(e.target.value)}
                  rows={3}
                />
              </div>
            </div>
            <div className={styles.modal__footer}>
              <button
                className={styles.modal__cancelBtn}
                onClick={() => setShowRevokeModal(false)}
              >
                取消
              </button>
              <button
                className={cn(styles.modal__confirmBtn, styles['modal__confirmBtn--danger'])}
                onClick={handleRevoke}
                disabled={!revokeReason || revokeMutation.isPending}
              >
                {revokeMutation.isPending ? '处理中...' : '确认撤销'}
              </button>
            </div>
          </div>
        </div>
      )}

    </PageContainer>
  );
}
