/**
 * 员工端 — 规章制度公示页面
 * 展示已公示制度列表，员工可阅读并签收确认
 */

import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { FileText, CheckCircle, Clock, ArrowLeft, ChevronRight, ScrollText } from 'lucide-react'
import { portalApi } from '../../lib/api-services'
import Card from '../../components/ui/Card'
import Button from '../../components/ui/Button'
import EmptyState from '../../components/ui/EmptyState'

export default function MyPolicies() {
  const queryClient = useQueryClient()
  const [selectedId, setSelectedId] = useState<string | null>(null)

  /** 已公示制度列表 */
  const { data: list, isLoading } = useQuery<any>({
    queryKey: ['portal-policies'],
    queryFn: async () => {
      return await portalApi.policies()
    },
  })

  /** 制度详情 */
  const { data: detail, isLoading: detailLoading } = useQuery<any>({
    queryKey: ['portal-policy', selectedId],
    queryFn: async () => {
      if (!selectedId) return null
      return await portalApi.policyDetail(selectedId)
    },
    enabled: !!selectedId,
  })

  /** 阅读确认 */
  const readMutation = useMutation({
    mutationFn: (id: string) => portalApi.policyRead(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['portal-policies'] })
      queryClient.invalidateQueries({ queryKey: ['portal-policy', selectedId] })
    },
  })

  /** 待签收数量 */
  const pendingCount = (list || []).filter((p: any) => !p.hasRead).length

  /** 详情页 */
  if (selectedId) {
    return (
      <div className="space-y-4">
        <button
          onClick={() => setSelectedId(null)}
          className="flex items-center gap-1 text-gray-500 hover:text-gray-700 text-sm py-2"
        >
          <ArrowLeft className="w-4 h-4" />返回列表
        </button>

        {detailLoading ? (
          <Card className="p-6">
            <div className="animate-pulse space-y-3">
              <div className="h-6 bg-gray-100 rounded w-2/3" />
              <div className="h-4 bg-gray-100 rounded w-1/3" />
              <div className="h-20 bg-gray-100 rounded w-full" />
            </div>
          </Card>
        ) : detail ? (
          <Card className="p-5">
            <div className="flex items-center gap-2 mb-3">
              <div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
                <FileText className="w-5 h-5 text-primary" />
              </div>
              <div className="flex-1 min-w-0">
                <h1 className="text-base font-semibold truncate">{detail.title}</h1>
                <div className="text-xs text-gray-500 mt-0.5">
                  公示时间：{detail.publishedAt?.slice(0, 10) || '-'}
                </div>
              </div>
            </div>

            {/* 签收状态徽章 */}
            <div className="mb-4">
              {detail.hasRead ? (
                <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs bg-green-100 text-green-700">
                  <CheckCircle className="w-3.5 h-3.5" />已签收
                </span>
              ) : (
                <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs bg-amber-100 text-amber-700">
                  <Clock className="w-3.5 h-3.5" />待签收
                </span>
              )}
            </div>

            {/* 制度正文 */}
            <div className="text-sm text-gray-700 whitespace-pre-wrap leading-relaxed mb-6">
              {detail.content || '暂无内容'}
            </div>

            {/* 签收操作 */}
            <div className="border-t pt-4">
              {detail.hasRead ? (
                <div className="text-center text-xs text-gray-500">
                  您已于 {detail.readAt?.slice(0, 19).replace('T', ' ')} 签收确认
                </div>
              ) : (
                <Button
                  className="w-full"
                  onClick={() => readMutation.mutate(detail.id)}
                  disabled={readMutation.isPending}
                >
                  {readMutation.isPending ? '确认中...' : '我已阅读并理解，确认签收'}
                </Button>
              )}
            </div>
          </Card>
        ) : (
          <Card className="p-6">
            <EmptyState title="制度不存在" description="该制度可能已被撤回" />
          </Card>
        )}
      </div>
    )
  }

  /** 列表页 */
  return (
    <div className="space-y-4">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <h1 className="text-lg font-bold text-gray-900">规章制度</h1>
        {pendingCount > 0 && (
          <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs bg-amber-100 text-amber-700">
            <Clock className="w-3.5 h-3.5" />
            {pendingCount} 项待签收
          </span>
        )}
      </div>

      {isLoading ? (
        <div className="space-y-2">
          {[1, 2, 3].map(i => (
            <Card key={i} className="p-4">
              <div className="animate-pulse flex items-center gap-3">
                <div className="w-10 h-10 bg-gray-100 rounded-xl" />
                <div className="flex-1 space-y-2">
                  <div className="h-4 bg-gray-100 rounded w-2/3" />
                  <div className="h-3 bg-gray-100 rounded w-1/3" />
                </div>
              </div>
            </Card>
          ))}
        </div>
      ) : !list || list.length === 0 ? (
        <Card className="p-6">
          <EmptyState title="暂无公示制度" description="公司尚未公示任何规章制度" />
        </Card>
      ) : (
        <div className="space-y-2">
          {list.map((p: any) => (
            <Card key={p.id} className="cursor-pointer hover:shadow-md transition-shadow">
              <div onClick={() => setSelectedId(p.id)} className="flex items-center gap-3 p-4">
                <div className={`w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 ${
                  p.hasRead ? 'bg-green-100' : 'bg-amber-100'
                }`}>
                  <ScrollText className={`w-5 h-5 ${p.hasRead ? 'text-green-600' : 'text-amber-600'}`} />
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-1.5">
                    <span className="text-sm font-medium truncate min-w-0">{p.title}</span>
                    {p.hasRead ? (
                      <span className="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs bg-green-100 text-green-700 flex-shrink-0">
                        <CheckCircle className="w-3 h-3" />已签收
                      </span>
                    ) : (
                      <span className="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs bg-amber-100 text-amber-700 flex-shrink-0">
                        <Clock className="w-3 h-3" />待签收
                      </span>
                    )}
                  </div>
                  <div className="text-xs text-gray-500 mt-1">
                    公示时间：{p.publishedAt?.slice(0, 10) || '-'}
                  </div>
                </div>
                <ChevronRight className="w-4 h-4 text-gray-300 flex-shrink-0" />
              </div>
            </Card>
          ))}
        </div>
      )}
    </div>
  )
}
