import { Button, Text, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useMemo, useState } from "react";
import { getAllEvaluationRecords, getEvaluationGuide, getMyEvaluation, type EvaluationSubmissionRecord } from "../../api/evaluation";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { useMemberGuard } from "../../hooks/useMemberGuard";
import "./index.scss";

const TYPE_LABELS: Record<string, string> = {
  EDUCATION: "教育经历",
  QUALIFICATION: "资质证书",
  POSITION: "社会兼职",
  AWARD: "荣获奖项",
  PROPOSAL: "建言献策",
  SERVICE: "社会服务",
  DUTY: "履职情况"
};

function firstText(...values: any[]) {
  for (const value of values) {
    if (value !== undefined && value !== null && String(value).trim()) return String(value).trim();
  }
  return "";
}

function recordTitle(record: EvaluationSubmissionRecord) {
  const row = record.row || {};
  return firstText(
    row.title,
    row.awardName,
    row.award_name,
    row.name,
    row.school,
    row.organizationName,
    row.organization_name,
    row.dutyType,
    row.duty_type,
    TYPE_LABELS[record.type]
  );
}

function recordDate(row: any) {
  return firstText(row.submissionDate, row.submission_date, row.awardDate, row.award_date, row.issuedAt, row.issued_at, row.startDate, row.start_date, row.period, row.createdAt, row.created_at).slice(0, 10);
}

function statusText(row: any) {
  const value = String(row.auditStatus || row.audit_status || row.status || "").toUpperCase();
  if (value === "APPROVED" || value === "PASSED") return "已通过";
  if (value === "REJECTED") return "已驳回";
  if (value === "PENDING" || value === "SUBMITTED") return "审核中";
  return value || "已记录";
}

export default function EvaluationPage() {
  useAuthGuard();
  useMemberGuard("成就档案仅面向正式会员开放");

  const [evaluation, setEvaluation] = useState<any>(null);
  const [guide, setGuide] = useState<any>(null);
  const [records, setRecords] = useState<EvaluationSubmissionRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const load = async () => {
    setLoading(true);
    try {
      const [evaluationData, guideData, recordData] = await Promise.all([
        getMyEvaluation().catch(() => null),
        getEvaluationGuide().catch(() => null),
        getAllEvaluationRecords()
      ]);
      setEvaluation(evaluationData);
      setGuide(guideData);
      setRecords(recordData);
      setError("");
    } catch (e: any) {
      setError(e?.message || "成就档案加载失败");
    } finally {
      setLoading(false);
    }
  };

  useDidShow(() => {
    void load();
  });

  const stats = useMemo(() => {
    const approved = records.filter((item) => statusText(item.row) === "已通过").length;
    const pending = records.filter((item) => statusText(item.row) === "审核中").length;
    const rejected = records.filter((item) => statusText(item.row) === "已驳回").length;
    return { total: records.length, approved, pending, rejected };
  }, [records]);

  const dimensions = Array.isArray(guide?.dimensions) ? guide.dimensions : [];
  const totalScore = firstText(evaluation?.totalScore, evaluation?.total_score, evaluation?.score);
  const grade = firstText(evaluation?.grade, evaluation?.latestEvaluationGrade, evaluation?.latest_evaluation_grade);
  const period = firstText(evaluation?.period, evaluation?.evaluationPeriod, guide?.period?.name, guide?.period);

  return (
    <View className="evaluation-page">
      <View className="evaluation-page__body">
        {error ? <Text className="evaluation-state is-error">{error}</Text> : null}
        {loading ? <Text className="evaluation-state">加载中...</Text> : null}

        <View className="evaluation-hero">
          <Text className="evaluation-hero__label">{period || "当前周期"}</Text>
          <Text className="evaluation-hero__score">{totalScore ? `${totalScore}分` : "暂无评分"}</Text>
          <Text className="evaluation-hero__grade">{grade ? `评价结果：${grade}` : "当前周期暂未生成评价结果"}</Text>
          <Button className="evaluation-hero__button" onClick={() => Taro.navigateTo({ url: "/pages/evaluation-material/index" })}>
            补充成就材料
          </Button>
        </View>

        <View className="evaluation-stats">
          <View><Text>{stats.total}</Text><Text>材料</Text></View>
          <View><Text>{stats.approved}</Text><Text>已通过</Text></View>
          <View><Text>{stats.pending}</Text><Text>审核中</Text></View>
          <View><Text>{stats.rejected}</Text><Text>已驳回</Text></View>
        </View>

        <View className="evaluation-panel">
          <Text className="evaluation-panel__title">评价维度</Text>
          {dimensions.length === 0 ? <Text className="evaluation-empty">暂无评价规则</Text> : null}
          {dimensions.map((item: any) => (
            <View key={item.code || item.name} className="evaluation-dimension">
              <View>
                <Text className="evaluation-dimension__name">{item.name || item.code}</Text>
                <Text className="evaluation-dimension__meta">权重 {item.weight || "-"} · 满分 {item.max || "-"}</Text>
              </View>
            </View>
          ))}
        </View>

        <View className="evaluation-panel">
          <View className="evaluation-panel__head">
            <Text className="evaluation-panel__title">最近材料</Text>
            <Text className="evaluation-panel__link" onClick={() => Taro.navigateTo({ url: "/pages/evaluation-material/index" })}>新增</Text>
          </View>
          {records.length === 0 ? <Text className="evaluation-empty">暂无成就材料</Text> : null}
          {records.slice(0, 30).map((record, index) => (
            <View key={`${record.type}-${record.row?.id || index}`} className="evaluation-record">
              <View className="evaluation-record__top">
                <Text className="evaluation-record__type">{TYPE_LABELS[record.type] || record.type}</Text>
                <Text className="evaluation-record__status">{statusText(record.row)}</Text>
              </View>
              <Text className="evaluation-record__title">{recordTitle(record)}</Text>
              <Text className="evaluation-record__meta">{recordDate(record.row) || "暂无日期"}</Text>
              {record.row?.review_reason || record.row?.audit_reason ? <Text className="evaluation-record__reason">原因：{record.row.review_reason || record.row.audit_reason}</Text> : null}
            </View>
          ))}
        </View>
      </View>
    </View>
  );
}
