import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Badge } from '../ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../ui/dialog';
import { Label } from '../ui/label';
import { Textarea } from '../ui/textarea';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { ScrollArea } from '../ui/scroll-area';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { Enterprise, AuditStatus } from '../../types/user-management';
import { Search, Eye, CheckCircle, XCircle, Building, FileText, CreditCard, User, Image as ImageIcon } from 'lucide-react';
import { toast } from 'sonner@2.0.3';

export function EnterpriseAudit() {
  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('已驳回');
  };

  const getAuditStatusBadge = (status: AuditStatus) => {
    switch (status) {
      case 'pending':
        return <Badge className="bg-yellow-100 text-yellow-700">待审核</Badge>;
      case 'approved':
        return <Badge className="bg-green-100 text-green-700">已通过</Badge>;
      case 'rejected':
        return <Badge className="bg-red-100 text-red-700">已驳回</Badge>;
      default:
        return <Badge>{status}</Badge>;
    }
  };

  const stats = [
    {
      label: '待审核',
      value: enterprises.filter(e => e.auditStatus === 'pending').length,
      color: 'text-yellow-600',
      bg: 'bg-yellow-100',
    },
    {
      label: '已通过',
      value: enterprises.filter(e => e.auditStatus === 'approved').length,
      color: 'text-green-600',
      bg: 'bg-green-100',
    },
    {
      label: '已驳回',
      value: enterprises.filter(e => e.auditStatus === 'rejected').length,
      color: 'text-red-600',
      bg: 'bg-red-100',
    },
    {
      label: '总企业数',
      value: enterprises.length,
      color: 'text-blue-600',
      bg: 'bg-blue-100',
    },
  ];

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

      {/* 统计卡片 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {stats.map((stat, index) => (
          <Card key={index} className="p-4">
            <div className="text-sm text-muted-foreground">{stat.label}</div>
            <div className={`mt-2 ${stat.color}`}>{stat.value}</div>
          </Card>
        ))}
      </div>

      {/* 搜索和筛选 */}
      <Card className="p-4">
        <div className="flex gap-4">
          <div className="flex-1">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
              <Input
                placeholder="搜索企业名称、信用代码、登记人..."
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>
          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger className="w-40">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部状态</SelectItem>
              <SelectItem value="pending">待审核</SelectItem>
              <SelectItem value="approved">已通过</SelectItem>
              <SelectItem value="rejected">已驳回</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </Card>

      {/* 企业列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>企业名称</TableHead>
              <TableHead>企业类型</TableHead>
              <TableHead>社会信用代码</TableHead>
              <TableHead>法人</TableHead>
              <TableHead>所在地区</TableHead>
              <TableHead>审核状态</TableHead>
              <TableHead>提交时间</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredEnterprises.length === 0 ? (
              <TableRow>
                <TableCell colSpan={8} className="text-center text-muted-foreground py-8">
                  暂无数据
                </TableCell>
              </TableRow>
            ) : (
              filteredEnterprises.map((enterprise) => (
                <TableRow key={enterprise.id}>
                  <TableCell>{enterprise.name}</TableCell>
                  <TableCell className="text-muted-foreground">{enterprise.type}</TableCell>
                  <TableCell className="text-muted-foreground">
                    <code className="text-xs">{enterprise.socialCreditCode}</code>
                  </TableCell>
                  <TableCell>{enterprise.legalPerson || '-'}</TableCell>
                  <TableCell>{`${enterprise.province} ${enterprise.city}`}</TableCell>
                  <TableCell>{getAuditStatusBadge(enterprise.auditStatus)}</TableCell>
                  <TableCell className="text-muted-foreground">
                    {new Date(enterprise.createdAt).toLocaleDateString('zh-CN')}
                  </TableCell>
                  <TableCell>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleViewDetail(enterprise)}
                    >
                      <Eye className="w-4 h-4 mr-1" />
                      查看
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>

      {/* 详情审核对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh]">
          <DialogHeader>
            <div className="flex items-center justify-between pr-8">
              <DialogTitle>企业详情审核</DialogTitle>
              {selectedEnterprise && getAuditStatusBadge(selectedEnterprise.auditStatus)}
            </div>
            <DialogDescription className="sr-only">
              查看企业的详细信息和审核状态
            </DialogDescription>
          </DialogHeader>
          {selectedEnterprise && (
            <ScrollArea className="max-h-[calc(90vh-200px)]">
              <Tabs defaultValue="basic" className="space-y-4">
                <TabsList className="grid grid-cols-4 w-full">
                  <TabsTrigger value="basic">
                    <Building className="w-4 h-4 mr-2" />
                    基本信息
                  </TabsTrigger>
                  <TabsTrigger value="other">
                    <FileText className="w-4 h-4 mr-2" />
                    其他信息
                  </TabsTrigger>
                  <TabsTrigger value="bank">
                    <CreditCard className="w-4 h-4 mr-2" />
                    开户信息
                  </TabsTrigger>
                  <TabsTrigger value="legal">
                    <User className="w-4 h-4 mr-2" />
                    法人信息
                  </TabsTrigger>
                </TabsList>

                {/* 企业基本信息 */}
                <TabsContent value="basic" className="space-y-4">
                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <Label>企业名称</Label>
                      <div className="field-value">{selectedEnterprise.name}</div>
                    </div>
                    <div>
                      <Label>企业类型</Label>
                      <div className="field-value">{selectedEnterprise.type}</div>
                    </div>
                    <div>
                      <Label>所在地区</Label>
                      <div className="field-value">
                        {selectedEnterprise.province} {selectedEnterprise.city} {selectedEnterprise.district}
                      </div>
                    </div>
                    <div>
                      <Label>详细地址</Label>
                      <div className="field-value">{selectedEnterprise.address}</div>
                    </div>
                    <div>
                      <Label>登记人</Label>
                      <div className="field-value">{selectedEnterprise.registrant}</div>
                    </div>
                    <div>
                      <Label>联系电话</Label>
                      <div className="field-value">{selectedEnterprise.contactPhone}</div>
                    </div>
                  </div>
                </TabsContent>

                {/* 其他信息 */}
                <TabsContent value="other" className="space-y-4">
                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <Label>公司规模</Label>
                      <div className="field-value">{selectedEnterprise.companySize || '-'}</div>
                    </div>
                    <div>
                      <Label>注册资本</Label>
                      <div className="field-value">{selectedEnterprise.registeredCapital || '-'}</div>
                    </div>
                    <div>
                      <Label>成立时间</Label>
                      <div className="field-value">{selectedEnterprise.establishmentDate || '-'}</div>
                    </div>
                    <div>
                      <Label>发票类型</Label>
                      <div className="field-value">{selectedEnterprise.invoiceType || '-'}</div>
                    </div>
                    <div className="col-span-2">
                      <Label>社会信用代码</Label>
                      <div className="field-value">
                        <code className="text-sm font-mono">
                          {selectedEnterprise.socialCreditCode}
                        </code>
                      </div>
                    </div>
                    <div className="col-span-2">
                      <Label>经营范围</Label>
                      <div className="field-value">{selectedEnterprise.businessScope || '-'}</div>
                    </div>
                    <div className="col-span-2">
                      <Label>营业执照</Label>
                      <div className="mt-2">
                        {selectedEnterprise.businessLicense ? (
                          <img
                            src={selectedEnterprise.businessLicense}
                            alt="营业执照"
                            className="w-64 h-auto border rounded-lg"
                          />
                        ) : (
                          <span className="text-muted-foreground">未上传</span>
                        )}
                      </div>
                    </div>
                  </div>
                </TabsContent>

                {/* 开户信息 */}
                <TabsContent value="bank" className="space-y-4">
                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <Label>银行账号</Label>
                      <div className="field-value">
                        {selectedEnterprise.bankAccount ? (
                          <code className="text-sm font-mono">
                            {selectedEnterprise.bankAccount}
                          </code>
                        ) : '-'}
                      </div>
                    </div>
                    <div>
                      <Label>开户行</Label>
                      <div className="field-value">{selectedEnterprise.bankName || '-'}</div>
                    </div>
                    <div className="col-span-2">
                      <Label>开户行全称</Label>
                      <div className="field-value">{selectedEnterprise.bankFullName || '-'}</div>
                    </div>
                    <div className="col-span-2">
                      <Label>开户行地址</Label>
                      <div className="field-value">{selectedEnterprise.bankAddress || '-'}</div>
                    </div>
                    <div className="col-span-2">
                      <Label>开户许可证</Label>
                      <div className="mt-2">
                        {selectedEnterprise.bankLicense ? (
                          <img
                            src={selectedEnterprise.bankLicense}
                            alt="开户许可证"
                            className="w-64 h-auto border rounded-lg"
                          />
                        ) : (
                          <span className="text-muted-foreground">未上传</span>
                        )}
                      </div>
                    </div>
                  </div>
                </TabsContent>

                {/* 法人信息 */}
                <TabsContent value="legal" className="space-y-4">
                  <div className="grid grid-cols-1 gap-6">
                    <div>
                      <Label>法人名称</Label>
                      <div className="field-value">{selectedEnterprise.legalPerson || '-'}</div>
                    </div>
                    <div>
                      <Label>身份证正面</Label>
                      <div className="mt-2">
                        {selectedEnterprise.idCardFront ? (
                          <img
                            src={selectedEnterprise.idCardFront}
                            alt="身份证正面"
                            className="w-80 h-auto border rounded-lg"
                          />
                        ) : (
                          <span className="text-muted-foreground">未上传</span>
                        )}
                      </div>
                    </div>
                    <div>
                      <Label>身份证反面</Label>
                      <div className="mt-2">
                        {selectedEnterprise.idCardBack ? (
                          <img
                            src={selectedEnterprise.idCardBack}
                            alt="身份证反面"
                            className="w-80 h-auto border rounded-lg"
                          />
                        ) : (
                          <span className="text-muted-foreground">未上传</span>
                        )}
                      </div>
                    </div>
                  </div>
                </TabsContent>
              </Tabs>

              {/* 审核信息 */}
              <div className="mt-6 pt-6 border-t">
                <h4 className="mb-4 font-bold">审核信息</h4>
                <Card className="p-6 bg-gray-50 border">
                  <div className="grid grid-cols-2 gap-x-8 gap-y-4">
                    <div>
                      <Label className="text-xs">提交时间</Label>
                      <div className="mt-1.5 text-base">
                        {new Date(selectedEnterprise.createdAt).toLocaleString('zh-CN')}
                      </div>
                    </div>
                    {selectedEnterprise.auditTime && (
                      <div>
                        <Label className="text-xs">审核时间</Label>
                        <div className="mt-1.5 text-base">
                          {new Date(selectedEnterprise.auditTime).toLocaleString('zh-CN')}
                        </div>
                      </div>
                    )}
                    {selectedEnterprise.auditor && (
                      <div>
                        <Label className="text-xs">审核人</Label>
                        <div className="mt-1.5 text-base">
                          {selectedEnterprise.auditor}
                        </div>
                      </div>
                    )}
                    {selectedEnterprise.auditReason && (
                      <div className="col-span-2 pt-4 mt-2 border-t">
                        <Label className="text-xs">审核意见</Label>
                        <div className="mt-1.5 text-base">
                          {selectedEnterprise.auditReason}
                        </div>
                      </div>
                    )}
                  </div>
                </Card>

                {/* 审核操作区 - 仅待审核状态显示 */}
                {selectedEnterprise.auditStatus === 'pending' && (
                  <div className="mt-6">
                    <Label>审核意见</Label>
                    <Textarea
                      value={auditReason}
                      onChange={(e) => setAuditReason(e.target.value)}
                      rows={3}
                      placeholder="请填写审核意见（驳回时必填）..."
                      className="mt-2"
                    />
                  </div>
                )}
              </div>
            </ScrollArea>
          )}
          <DialogFooter className="border-t pt-4">
            <Button variant="outline" onClick={() => setShowDetailDialog(false)}>
              关闭
            </Button>
            {selectedEnterprise?.auditStatus === 'pending' && (
              <>
                <Button
                  variant="destructive"
                  onClick={handleReject}
                >
                  <XCircle className="w-4 h-4 mr-2" />
                  驳回
                </Button>
                <Button onClick={handleApprove}>
                  <CheckCircle className="w-4 h-4 mr-2" />
                  通过
                </Button>
              </>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
