'use client';

import { useState, useEffect } from 'react';
import { toast } from 'sonner';
import { AuditStatsCards } from './components/AuditStatsCards';
import { SearchFilters } from './components/SearchFilters';
import { EnterpriseList } from './components/EnterpriseList';
import { EnterpriseDetailDialog } from './components/EnterpriseDetailDialog';
import { Enterprise, AuditStatus } from './types';

export default function EnterpriseAuditPage() {
  const [enterprises, setEnterprises] = useState<Enterprise[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [selectedEnterprise, setSelectedEnterprise] = useState<Enterprise | null>(null);
  const [auditReason, setAuditReason] = useState('');

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

  const loadEnterprises = () => {
    const data = localStorage.getItem('smart_agriculture_enterprises');
    if (data) {
      setEnterprises(JSON.parse(data));
    } else {
      // 初始化示例数据
      const mockEnterprises: Enterprise[] = [
        {
          id: 'ent-1',
          name: '绿野农业科技有限公司',
          type: '有限责任公司',
          province: '北京市',
          city: '海淀区',
          district: '中关村街道',
          companySize: '50-200人',
          registeredCapital: '1000万元',
          establishmentDate: '2020-03-15',
          invoiceType: '增值税专用发票',
          socialCreditCode: '91110000123456789X',
          businessScope: '农业技术开发、技术咨询、技术服务；销售机械设备、电子产品。',
          bankAccount: '1234567890123456789',
          bankName: '中国工商银行',
          bankFullName: '中国工商银行股份有限公司北京中关村支行',
          bankAddress: '北京市海淀区中关村大街1号',
          legalPerson: '张伟',
          registrant: '张经理',
          contactPhone: '13800138001',
          address: '北京市海淀区中关村大街1号科技大厦',
          status: 'active',
          auditStatus: 'pending',
          createdAt: '2024-10-10T08:00:00',
          updatedAt: '2024-10-10T08:00:00',
        },
        {
          id: 'ent-2',
          name: '丰收现代农业集团',
          type: '股份有限公司',
          province: '江苏省',
          city: '南京市',
          district: '江宁区',
          companySize: '200-500人',
          registeredCapital: '5000万元',
          establishmentDate: '2018-06-20',
          invoiceType: '增值税专用发票',
          socialCreditCode: '91320000987654321Y',
          businessScope: '现代农业种植、农产品加工与销售、农业技术推广服务。',
          bankAccount: '9876543210987654321',
          bankName: '中国农业银行',
          bankFullName: '中国农业银行股份有限公司南京江宁支行',
          bankAddress: '江苏省南京市江宁区农业大道88号',
          legalPerson: '李明',
          registrant: '李总',
          contactPhone: '13900139002',
          address: '江苏省南京市江宁区农业大道88号',
          status: 'active',
          auditStatus: 'approved',
          auditTime: '2024-10-08T14:30:00',
          auditor: '系统管理员',
          createdAt: '2024-10-05T10:00:00',
          updatedAt: '2024-10-08T14:30:00',
        },
        {
          id: 'ent-3',
          name: '金穗农机服务中心',
          type: '个人独资企业',
          province: '山东省',
          city: '济南市',
          district: '历城区',
          companySize: '1-50人',
          registeredCapital: '200万元',
          establishmentDate: '2021-09-10',
          invoiceType: '增值税普通发票',
          socialCreditCode: '91370000456789012Z',
          businessScope: '农业机械租赁、维修服务、农机作业服务。',
          bankAccount: '5555666677778888',
          bankName: '中国建设银行',
          bankFullName: '中国建设银行股份有限公司济南历城支行',
          bankAddress: '山东省济南市历城区农机路66号',
          legalPerson: '王刚',
          registrant: '王主任',
          contactPhone: '13700137003',
          address: '山东省济南市历城区农机路66号',
          status: 'inactive',
          auditStatus: 'rejected',
          auditReason: '资质材料不完整，请补充营业执照副本和法人身份证复印件',
          auditTime: '2024-10-09T16:00:00',
          auditor: '系统管理员',
          createdAt: '2024-10-06T09:00:00',
          updatedAt: '2024-10-09T16:00:00',
        },
      ];
      localStorage.setItem('smart_agriculture_enterprises', JSON.stringify(mockEnterprises));
      setEnterprises(mockEnterprises);
    }
  };

  const filteredEnterprises = enterprises.filter(ent => {
    const matchKeyword = !searchKeyword ||
      ent.name.includes(searchKeyword) ||
      ent.socialCreditCode.includes(searchKeyword) ||
      ent.registrant.includes(searchKeyword);

    const matchStatus = statusFilter === 'all' || ent.auditStatus === statusFilter;

    return matchKeyword && matchStatus;
  });

  const handleViewDetail = (enterprise: Enterprise) => {
    setSelectedEnterprise(enterprise);
    setAuditReason('');
    setShowDetailDialog(true);
  };

  const handleApprove = () => {
    if (!selectedEnterprise) return;

    const now = new Date().toISOString();
    const updated = enterprises.map(ent =>
      ent.id === selectedEnterprise.id
        ? {
            ...ent,
            auditStatus: 'approved' as AuditStatus,
            status: 'active' as const,
            auditTime: now,
            auditor: '系统管理员',
            auditReason: auditReason || undefined,
            updatedAt: now,
          }
        : ent
    );

    // 创建审核历史记录
    const auditRecords = JSON.parse(localStorage.getItem('smart_agriculture_audit_records') || '[]');
    const newRecord = {
      id: `audit-${Date.now()}`,
      enterpriseId: selectedEnterprise.id,
      enterpriseName: selectedEnterprise.name,
      auditType: 'register',
      submitTime: selectedEnterprise.createdAt,
      auditTime: now,
      auditor: '系统管理员',
      result: 'approved',
      remarks: auditReason || '审核通过',
    };
    auditRecords.push(newRecord);
    localStorage.setItem('smart_agriculture_audit_records', JSON.stringify(auditRecords));

    setEnterprises(updated);
    localStorage.setItem('smart_agriculture_enterprises', JSON.stringify(updated));
    setShowDetailDialog(false);
    toast.success('审核通过');
  };

  const handleReject = () => {
    if (!selectedEnterprise) return;
    if (!auditReason.trim()) {
      toast.error('请填写驳回原因');
      return;
    }

    const now = new Date().toISOString();
    const updated = enterprises.map(ent =>
      ent.id === selectedEnterprise.id
        ? {
            ...ent,
            auditStatus: 'rejected' as AuditStatus,
            status: 'inactive' as const,
            auditTime: now,
            auditor: '系统管理员',
            auditReason: auditReason,
            updatedAt: now,
          }
        : ent
    );

    // 创建审核历史记录
    const auditRecords = JSON.parse(localStorage.getItem('smart_agriculture_audit_records') || '[]');
    const newRecord = {
      id: `audit-${Date.now()}`,
      enterpriseId: selectedEnterprise.id,
      enterpriseName: selectedEnterprise.name,
      auditType: 'register',
      submitTime: selectedEnterprise.createdAt,
      auditTime: now,
      auditor: '系统管理员',
      result: 'rejected',
      reason: auditReason,
      remarks: '审核驳回',
    };
    auditRecords.push(newRecord);
    localStorage.setItem('smart_agriculture_audit_records', JSON.stringify(auditRecords));

    setEnterprises(updated);
    localStorage.setItem('smart_agriculture_enterprises', JSON.stringify(updated));
    setShowDetailDialog(false);
    toast.success('已驳回');
  };

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-green-800">企业审核</h2>
        <p className="text-muted-foreground">管理企业注册与变更审核流程</p>
      </div>

      {/* 统计卡片 */}
      <AuditStatsCards enterprises={enterprises} />

      {/* 搜索和筛选 */}
      <SearchFilters
        searchKeyword={searchKeyword}
        setSearchKeyword={setSearchKeyword}
        statusFilter={statusFilter}
        setStatusFilter={setStatusFilter}
      />

      {/* 企业列表 */}
      <EnterpriseList
        enterprises={filteredEnterprises}
        onViewDetail={handleViewDetail}
      />

      {/* 详情审核对话框 */}
      <EnterpriseDetailDialog
        enterprise={selectedEnterprise}
        open={showDetailDialog}
        onOpenChange={setShowDetailDialog}
        auditReason={auditReason}
        onAuditReasonChange={setAuditReason}
        onApprove={handleApprove}
        onReject={handleReject}
      />
    </div>
  );
}