'use client';

import { useState, useEffect } from 'react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Download } from 'lucide-react';
import { AuditHistoryStatsCards } from './components/AuditHistoryStatsCards';
import { AuditHistoryFilters } from './components/AuditHistoryFilters';
import { AuditHistoryList } from './components/AuditHistoryList';
import { AuditHistoryDetailDialog } from './components/AuditHistoryDetailDialog';
import { AuditHistoryInstructions } from './components/AuditHistoryInstructions';
import { AuditRecord, Enterprise, FilterOptions } from './types';

export default function AuditHistoryPage() {
  const [records, setRecords] = useState<AuditRecord[]>([]);
  const [enterprises, setEnterprises] = useState<Enterprise[]>([]);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [selectedRecord, setSelectedRecord] = useState<AuditRecord | null>(null);
  const [selectedEnterprise, setSelectedEnterprise] = useState<Enterprise | null>(null);

  const [filters, setFilters] = useState<FilterOptions>({
    searchKeyword: '',
    resultFilter: 'all',
    typeFilter: 'all',
    dateRange: 'all'
  });

  useEffect(() => {
    loadEnterprises();
    loadAuditHistory();
  }, []);

  const loadEnterprises = () => {
    const data = localStorage.getItem('smart_agriculture_enterprises');
    if (data) {
      setEnterprises(JSON.parse(data));
    }
  };

  const loadAuditHistory = () => {
    const data = localStorage.getItem('smart_agriculture_audit_records');
    if (data) {
      setRecords(JSON.parse(data));
    } else {
      // 初始化审核历史数据
      const mockRecords: AuditRecord[] = [
        {
          id: 'audit-1',
          enterpriseId: 'ent-2',
          enterpriseName: '丰收现代农业集团',
          auditType: 'register',
          submitTime: '2024-10-05T10:00:00',
          auditTime: '2024-10-08T14:30:00',
          auditor: '系统管理员',
          result: 'approved',
          remarks: '企业资质完整，审核通过',
        },
        {
          id: 'audit-2',
          enterpriseId: 'ent-3',
          enterpriseName: '金穗农机服务中心',
          auditType: 'register',
          submitTime: '2024-10-06T09:00:00',
          auditTime: '2024-10-09T16:00:00',
          auditor: '系统管理员',
          result: 'rejected',
          reason: '资质材料不完整，请补充营业执照副本',
          remarks: '缺少必要的资质证明文件',
        },
        {
          id: 'audit-3',
          enterpriseId: 'ent-1',
          enterpriseName: '绿野农业科技有限公司',
          auditType: 'register',
          submitTime: '2024-10-10T08:00:00',
          result: 'pending',
        },
        {
          id: 'audit-4',
          enterpriseId: 'ent-2',
          enterpriseName: '丰收现代农业集团',
          auditType: 'update',
          submitTime: '2024-10-12T15:30:00',
          auditTime: '2024-10-13T10:00:00',
          auditor: '系统管理员',
          result: 'approved',
          remarks: '企业地址变更审核通过',
        },
        {
          id: 'audit-5',
          enterpriseId: 'ent-4',
          enterpriseName: '智慧农田科技公司',
          auditType: 'register',
          submitTime: '2024-09-28T11:00:00',
          auditTime: '2024-09-30T09:30:00',
          auditor: '系统管理员',
          result: 'approved',
          remarks: '优质企业，快速审核通过',
        },
        {
          id: 'audit-6',
          enterpriseId: 'ent-5',
          enterpriseName: '农业机械租赁中心',
          auditType: 'register',
          submitTime: '2024-10-03T14:20:00',
          auditTime: '2024-10-05T11:00:00',
          auditor: '系统管理员',
          result: 'rejected',
          reason: '企业经营范围与平台业务不符',
          remarks: '建议企业完善相关资质后重新申请',
        },
      ];
      localStorage.setItem('smart_agriculture_audit_records', JSON.stringify(mockRecords));
      setRecords(mockRecords);
    }
  };

  const filteredRecords = records.filter(record => {
    const matchKeyword = !filters.searchKeyword ||
      record.enterpriseName.includes(filters.searchKeyword) ||
      (record.auditor && record.auditor.includes(filters.searchKeyword));

    const matchResult = filters.resultFilter === 'all' || record.result === filters.resultFilter;
    const matchType = filters.typeFilter === 'all' || record.auditType === filters.typeFilter;

    // 日期筛选
    let matchDate = true;
    if (filters.dateRange !== 'all' && record.auditTime) {
      const auditDate = new Date(record.auditTime);
      const now = new Date();
      const diffDays = Math.floor((now.getTime() - auditDate.getTime()) / (1000 * 60 * 60 * 24));

      switch (filters.dateRange) {
        case 'today':
          matchDate = diffDays === 0;
          break;
        case 'week':
          matchDate = diffDays <= 7;
          break;
        case 'month':
          matchDate = diffDays <= 30;
          break;
        case 'quarter':
          matchDate = diffDays <= 90;
          break;
      }
    }

    return matchKeyword && matchResult && matchType && matchDate;
  });

  const handleViewDetail = (record: AuditRecord) => {
    setSelectedRecord(record);
    // 查找对应的企业信息
    const enterprise = enterprises.find(e => e.id === record.enterpriseId);
    setSelectedEnterprise(enterprise || null);
    setShowDetailDialog(true);
  };

  const handleExport = () => {
    const dataStr = JSON.stringify(filteredRecords, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `audit_history_${new Date().getTime()}.json`;
    link.click();
    toast.success('审核历史数据导出成功');
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">审核历史</h2>
          <p className="text-muted-foreground">追溯查询全部企业的历史审核记录</p>
        </div>
        <Button onClick={handleExport}>
          <Download className="w-4 h-4 mr-2" />
          导出记录
        </Button>
      </div>

      {/* 统计卡片 */}
      <AuditHistoryStatsCards records={records} />

      {/* 搜索和筛选 */}
      <AuditHistoryFilters
        filters={filters}
        onFiltersChange={setFilters}
      />

      {/* 审核历史列表 */}
      <AuditHistoryList
        records={filteredRecords}
        onViewDetail={handleViewDetail}
      />

      {/* 详情对话框 */}
      <AuditHistoryDetailDialog
        record={selectedRecord}
        enterprise={selectedEnterprise}
        open={showDetailDialog}
        onOpenChange={setShowDetailDialog}
      />

      {/* 使用说明 */}
      <AuditHistoryInstructions />
    </div>
  );
}