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 { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../ui/dialog';
import { Label } from '../ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { ScrollArea } from '../ui/scroll-area';
import { AuditRecord, Enterprise } from '../../types/user-management';
import { Search, Eye, Calendar, FileText, Download, Building, CreditCard, User, Image as ImageIcon } from 'lucide-react';
import { toast } from 'sonner@2.0.3';

export function AuditHistory() {
  const [records, setRecords] = useState<AuditRecord[]>([]);
  const [enterprises, setEnterprises] = useState<Enterprise[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [resultFilter, setResultFilter] = useState<string>('all');
  const [typeFilter, setTypeFilter] = useState<string>('all');
  const [dateRange, setDateRange] = useState<string>('all');
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [selectedRecord, setSelectedRecord] = useState<AuditRecord | null>(null);
  const [selectedEnterprise, setSelectedEnterprise] = useState<Enterprise | null>(null);

  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 = !searchKeyword ||
      record.enterpriseName.includes(searchKeyword) ||
      (record.auditor && record.auditor.includes(searchKeyword));

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

    // 日期筛选
    let matchDate = true;
    if (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 (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('审核历史数据导出成功');
  };

  const getResultBadge = (result: string) => {
    switch (result) {
      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>{result}</Badge>;
    }
  };

  const getTypeBadge = (type: string) => {
    switch (type) {
      case 'register':
        return <Badge className="bg-blue-100 text-blue-700">注册审核</Badge>;
      case 'update':
        return <Badge className="bg-purple-100 text-purple-700">变更审核</Badge>;
      default:
        return <Badge>{type}</Badge>;
    }
  };

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

  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>

      {/* 统计卡片 */}
      <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="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div className="md:col-span-2">
            <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={typeFilter} onValueChange={setTypeFilter}>
            <SelectTrigger>
              <SelectValue placeholder="审核类型" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部类型</SelectItem>
              <SelectItem value="register">注册审核</SelectItem>
              <SelectItem value="update">变更审核</SelectItem>
            </SelectContent>
          </Select>
          <Select value={resultFilter} onValueChange={setResultFilter}>
            <SelectTrigger>
              <SelectValue placeholder="审核结果" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部结果</SelectItem>
              <SelectItem value="pending">待审核</SelectItem>
              <SelectItem value="approved">已通过</SelectItem>
              <SelectItem value="rejected">已驳回</SelectItem>
            </SelectContent>
          </Select>
        </div>
        <div className="mt-4">
          <Label className="text-sm text-muted-foreground mb-2 block">时间范围</Label>
          <div className="flex gap-2">
            {[
              { value: 'all', label: '全部' },
              { value: 'today', label: '今天' },
              { value: 'week', label: '近7天' },
              { value: 'month', label: '近30天' },
              { value: 'quarter', label: '近90天' },
            ].map((option) => (
              <Button
                key={option.value}
                variant={dateRange === option.value ? 'default' : 'outline'}
                size="sm"
                onClick={() => setDateRange(option.value)}
              >
                {option.label}
              </Button>
            ))}
          </div>
        </div>
      </Card>

      {/* 审核历史列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>企业名称</TableHead>
              <TableHead>审核类型</TableHead>
              <TableHead>提交时间</TableHead>
              <TableHead>审核时间</TableHead>
              <TableHead>审核人</TableHead>
              <TableHead>审核结果</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredRecords.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center text-muted-foreground py-8">
                  暂无审核记录
                </TableCell>
              </TableRow>
            ) : (
              filteredRecords.map((record) => (
                <TableRow key={record.id}>
                  <TableCell>{record.enterpriseName}</TableCell>
                  <TableCell>{getTypeBadge(record.auditType)}</TableCell>
                  <TableCell className="text-muted-foreground">
                    {new Date(record.submitTime).toLocaleString('zh-CN')}
                  </TableCell>
                  <TableCell className="text-muted-foreground">
                    {record.auditTime
                      ? new Date(record.auditTime).toLocaleString('zh-CN')
                      : '-'}
                  </TableCell>
                  <TableCell className="text-muted-foreground">{record.auditor || '-'}</TableCell>
                  <TableCell>{getResultBadge(record.result)}</TableCell>
                  <TableCell>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleViewDetail(record)}
                    >
                      <Eye className="w-4 h-4" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>

      {/* 详情对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh]">
          <DialogHeader>
            <DialogTitle>
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <FileText className="w-5 h-5 text-green-600" />
                  <span>审核记录详情</span>
                </div>
                {selectedRecord && (
                  <div className="flex items-center gap-2">
                    {getResultBadge(selectedRecord.result)}
                  </div>
                )}
              </div>
            </DialogTitle>
            <DialogDescription className="sr-only">
              查看企业审核的历史记录详情
            </DialogDescription>
          </DialogHeader>
          <ScrollArea className="max-h-[calc(90vh-120px)]">
            {selectedRecord && selectedEnterprise && (
              <div className="space-y-6 pr-6">
                {/* 企业信息标签页 */}
                <Tabs defaultValue="basic" className="w-full">
                  <TabsList className="grid w-full grid-cols-4">
                    <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">
                          {getTypeBadge(selectedRecord.auditType)}
                        </div>
                      </div>
                      <div>
                        <Label className="text-xs">提交时间</Label>
                        <div className="mt-1.5 text-base">
                          {new Date(selectedRecord.submitTime).toLocaleString('zh-CN')}
                        </div>
                      </div>
                      {selectedRecord.auditTime && (
                        <div>
                          <Label className="text-xs">审核时间</Label>
                          <div className="mt-1.5 text-base">
                            {new Date(selectedRecord.auditTime).toLocaleString('zh-CN')}
                          </div>
                        </div>
                      )}
                      {selectedRecord.auditor && (
                        <div>
                          <Label className="text-xs">审核人</Label>
                          <div className="mt-1.5 text-base">
                            {selectedRecord.auditor}
                          </div>
                        </div>
                      )}
                      {selectedRecord.reason && (
                        <div className="col-span-2 pt-4 mt-2 border-t">
                          <Label className="text-xs">驳回原因</Label>
                          <div className="mt-1.5 text-base text-red-800">
                            {selectedRecord.reason}
                          </div>
                        </div>
                      )}
                      {selectedRecord.remarks && (
                        <div className="col-span-2 pt-4 mt-2 border-t">
                          <Label className="text-xs">审核备注</Label>
                          <div className="mt-1.5 text-base">
                            {selectedRecord.remarks}
                          </div>
                        </div>
                      )}
                    </div>
                  </Card>
                </div>

                {/* 审核流程时间线 */}
                <div className="pt-6 border-t">
                  <h4 className="mb-4 font-bold">审核流程</h4>
                  <div className="space-y-4">
                    <div className="flex items-start gap-3">
                      <div className="w-2 h-2 rounded-full bg-blue-600 mt-2" />
                      <div>
                        <div className="text-sm">提交审核</div>
                        <div className="text-xs text-muted-foreground">
                          {new Date(selectedRecord.submitTime).toLocaleString('zh-CN')}
                        </div>
                      </div>
                    </div>
                    {selectedRecord.auditTime && (
                      <div className="flex items-start gap-3">
                        <div className={`w-2 h-2 rounded-full mt-2 ${
                          selectedRecord.result === 'approved' ? 'bg-green-600' : 'bg-red-600'
                        }`} />
                        <div>
                          <div className="text-sm">
                            {selectedRecord.result === 'approved' ? '审核通过' : '审核驳回'}
                          </div>
                          <div className="text-xs text-muted-foreground">
                            {new Date(selectedRecord.auditTime).toLocaleString('zh-CN')}
                            {selectedRecord.auditor && ` · ${selectedRecord.auditor}`}
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            )}
          </ScrollArea>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDetailDialog(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 使用说明 */}
      <Card className="p-4 bg-blue-50 border-blue-200">
        <h4 className="text-blue-900 mb-2">
          <Calendar className="w-4 h-4 inline mr-2" />
          审核历史说明
        </h4>
        <ul className="space-y-1 text-sm text-blue-800">
          <li>• 完整记录所有企业的注册和变更审核历史</li>
          <li>• 支持按企业名称、审核时间、审核结果等多维度筛选</li>
          <li>• 包含审核人员、审核时间、审核结果及备注等完整信息</li>
          <li>• 提供审核流程时间线，清晰展示审核进度</li>
          <li>• 支持导出审核记录，满足审计和稽查需求</li>
        </ul>
      </Card>
    </div>
  );
}
