'use client';

import { useReducer, useMemo } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Building2, Plus, Eye, Power, PowerOff, Search, Hash, FileText, CreditCard, User } from 'lucide-react';
import { toast } from 'sonner';

// Types
interface Enterprise {
  id: string;
  name: string;
  code: string;
  type: string;
  status: 'active' | 'inactive';
  auditStatus: 'not_submitted' | 'pending' | 'approved' | 'rejected';
  createdAt: string;
  contact?: string;
  phone?: string;
  contactPhone?: string;
  province?: string;
  city?: string;
  district?: string;
  address?: string;
  registrant?: string;
  companySize?: string;
  registeredCapital?: string;
  establishmentDate?: string;
  invoiceType?: string;
  socialCreditCode?: string;
  businessScope?: string;
  businessLicense?: string;
  bankAccount?: string;
  bankName?: string;
  bankFullName?: string;
  bankAddress?: string;
  bankLicense?: string;
  legalPerson?: string;
  idCardFront?: string;
  idCardBack?: string;
}

interface FormData {
  name: string;
  code: string;
  type: string;
}

interface EnterpriseState {
  enterprises: Enterprise[];
  showAddDialog: boolean;
  showViewDialog: boolean;
  showStatusDialog: boolean;
  selectedEnterprise: Enterprise | null;
  searchText: string;
  statusAction: 'enable' | 'disable';
  formData: FormData;
}

type EnterpriseAction =
  | { type: 'SET_ENTERPRISES'; payload: Enterprise[] }
  | { type: 'TOGGLE_ADD_DIALOG'; payload: boolean }
  | { type: 'TOGGLE_VIEW_DIALOG'; payload: boolean }
  | { type: 'TOGGLE_STATUS_DIALOG'; payload: boolean }
  | { type: 'SET_SELECTED_ENTERPRISE'; payload: Enterprise | null }
  | { type: 'SET_SEARCH_TEXT'; payload: string }
  | { type: 'SET_STATUS_ACTION'; payload: 'enable' | 'disable' }
  | { type: 'UPDATE_FORM_DATA'; payload: Partial<FormData> }
  | { type: 'RESET_FORM_DATA' }
  | { type: 'ADD_ENTERPRISE'; payload: Enterprise }
  | { type: 'UPDATE_ENTERPRISE_STATUS'; payload: { id: string; status: 'active' | 'inactive' } };

// Mock data
const mockEnterprises: Enterprise[] = [
  {
    id: 'ent-001',
    name: '智慧农业科技有限公司',
    code: 'ZHNY001',
    type: '科技企业',
    status: 'active',
    auditStatus: 'approved',
    createdAt: '2024-01-15 10:30:00',
    contact: '张三',
    phone: '13800138000',
    contactPhone: '13800138000',
    province: '北京市',
    city: '北京市',
    district: '海淀区',
    address: '中关村大街1号',
    registrant: '李四',
    companySize: '100-500人',
    registeredCapital: '1000万元',
    establishmentDate: '2020-01-01',
    invoiceType: '增值税专用发票',
    socialCreditCode: '91110108MA01XXXXXX',
    businessScope: '技术开发、技术服务、技术咨询',
    legalPerson: '王五'
  },
  {
    id: 'ent-002',
    name: '绿色农业合作社',
    code: 'LSNY002',
    type: '合作社',
    status: 'active',
    auditStatus: 'pending',
    createdAt: '2024-02-20 14:15:00',
    contact: '赵六',
    phone: '13900139000'
  },
  {
    id: 'ent-003',
    name: '现代农业发展有限公司',
    code: 'XDNY003',
    type: '农业企业',
    status: 'inactive',
    auditStatus: 'not_submitted',
    createdAt: '2024-03-10 09:45:00',
    contact: '钱七',
    phone: '13700137000'
  }
];

// Initial state
const initialState: EnterpriseState = {
  enterprises: mockEnterprises,
  showAddDialog: false,
  showViewDialog: false,
  showStatusDialog: false,
  selectedEnterprise: null,
  searchText: '',
  statusAction: 'enable',
  formData: {
    name: '',
    code: '',
    type: ''
  }
};

// Reducer
function enterpriseReducer(state: EnterpriseState, action: EnterpriseAction): EnterpriseState {
  switch (action.type) {
    case 'SET_ENTERPRISES':
      return { ...state, enterprises: action.payload };

    case 'TOGGLE_ADD_DIALOG':
      return {
        ...state,
        showAddDialog: action.payload,
        ...(action.payload === false ? { formData: initialState.formData } : {})
      };

    case 'TOGGLE_VIEW_DIALOG':
      return { ...state, showViewDialog: action.payload };

    case 'TOGGLE_STATUS_DIALOG':
      return { ...state, showStatusDialog: action.payload };

    case 'SET_SELECTED_ENTERPRISE':
      return { ...state, selectedEnterprise: action.payload };

    case 'SET_SEARCH_TEXT':
      return { ...state, searchText: action.payload };

    case 'SET_STATUS_ACTION':
      return { ...state, statusAction: action.payload };

    case 'UPDATE_FORM_DATA':
      return {
        ...state,
        formData: { ...state.formData, ...action.payload }
      };

    case 'RESET_FORM_DATA':
      return { ...state, formData: initialState.formData };

    case 'ADD_ENTERPRISE':
      return {
        ...state,
        enterprises: [...state.enterprises, action.payload]
      };

    case 'UPDATE_ENTERPRISE_STATUS':
      return {
        ...state,
        enterprises: state.enterprises.map(ent =>
          ent.id === action.payload.id
            ? { ...ent, status: action.payload.status }
            : ent
        )
      };

    default:
      return state;
  }
}

// Utility functions
const getStatusBadge = (status: 'active' | 'inactive') => {
  if (status === 'active') {
    return <Badge className="bg-green-100 text-green-800">启用</Badge>;
  }
  return <Badge className="bg-gray-100 text-gray-800">禁用</Badge>;
};

const getAuditStatusBadge = (auditStatus?: 'not_submitted' | 'pending' | 'approved' | 'rejected') => {
  switch (auditStatus) {
    case 'not_submitted':
      return <Badge className="bg-gray-100 text-gray-700">未提交</Badge>;
    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 className="bg-gray-100 text-gray-700">未提交</Badge>;
  }
};

export default function EnterpriseManagement() {
  const [state, dispatch] = useReducer(enterpriseReducer, initialState);

  // Computed values
  const filteredEnterprises = useMemo(() => {
    return state.enterprises.filter(ent => {
      if (!state.searchText) return true;
      const searchLower = state.searchText.toLowerCase();
      return (
        ent.name.toLowerCase().includes(searchLower) ||
        ent.code.toLowerCase().includes(searchLower) ||
        (ent.type && ent.type.toLowerCase().includes(searchLower))
      );
    });
  }, [state.enterprises, state.searchText]);

  const stats = useMemo(() => ({
    total: state.enterprises.length,
    active: state.enterprises.filter(e => e.status === 'active').length,
    inactive: state.enterprises.filter(e => e.status === 'inactive').length,
  }), [state.enterprises]);

  // Event handlers
  const handleAdd = () => {
    dispatch({ type: 'RESET_FORM_DATA' });
    dispatch({ type: 'TOGGLE_ADD_DIALOG', payload: true });
  };

  const handleView = (enterprise: Enterprise) => {
    dispatch({ type: 'SET_SELECTED_ENTERPRISE', payload: enterprise });
    dispatch({ type: 'TOGGLE_VIEW_DIALOG', payload: true });
  };

  const handleStatusChange = (enterprise: Enterprise, action: 'enable' | 'disable') => {
    dispatch({ type: 'SET_SELECTED_ENTERPRISE', payload: enterprise });
    dispatch({ type: 'SET_STATUS_ACTION', payload: action });
    dispatch({ type: 'TOGGLE_STATUS_DIALOG', payload: true });
  };

  const confirmAdd = () => {
    const { formData } = state;

    if (!formData.name.trim()) {
      toast.error('请输入企业名称');
      return;
    }
    if (!formData.code.trim()) {
      toast.error('请输入企业编码');
      return;
    }

    // 检查编码是否重复
    if (state.enterprises.some(e => e.code === formData.code)) {
      toast.error('企业编码已存在');
      return;
    }

    const newEnterprise: Enterprise = {
      id: `ent-${Date.now()}`,
      name: formData.name,
      code: formData.code,
      type: formData.type || '未分类',
      status: 'active',
      auditStatus: 'not_submitted',
      createdAt: new Date().toISOString().replace('T', ' ').substring(0, 19),
    };

    dispatch({ type: 'ADD_ENTERPRISE', payload: newEnterprise });
    dispatch({ type: 'TOGGLE_ADD_DIALOG', payload: false });
    toast.success('企业创建成功');
  };

  const confirmStatusChange = () => {
    if (!state.selectedEnterprise) return;

    const newStatus = state.statusAction === 'enable' ? 'active' : 'inactive';

    dispatch({
      type: 'UPDATE_ENTERPRISE_STATUS',
      payload: { id: state.selectedEnterprise.id, status: newStatus }
    });

    dispatch({ type: 'TOGGLE_STATUS_DIALOG', payload: false });
    toast.success(state.statusAction === 'enable' ? '企业已启用' : '企业已禁用');
  };

  const updateFormData = (field: keyof FormData, value: string) => {
    dispatch({ type: 'UPDATE_FORM_DATA', payload: { [field]: value || '' } });
  };

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <Card className="p-6 bg-gradient-to-r from-blue-50 to-indigo-50 border-blue-200">
        <div className="flex items-start gap-3">
          <Building2 className="w-6 h-6 text-blue-600 flex-shrink-0 mt-1" />
          <div className="flex-1">
            <h2 className="text-green-800 mb-2">企业管理</h2>
            <p className="text-sm text-muted-foreground mb-3">
              管理平台所有企业信息，支持创建企业、查看详情、启用/禁用企业
            </p>
            <div className="flex flex-wrap gap-2">
              <Badge variant="outline" className="bg-white">
                <Plus className="w-3 h-3 mr-1" />
                快速创建
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Power className="w-3 h-3 mr-1" />
                状态管理
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Eye className="w-3 h-3 mr-1" />
                详情查看
              </Badge>
            </div>
          </div>
        </div>
      </Card>

      {/* Statistics Cards */}
      <div className="grid grid-cols-3 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">企业总数</div>
            <Building2 className="w-5 h-5 text-blue-500" />
          </div>
          <div className="text-3xl font-bold mb-1">{stats.total}</div>
          <div className="text-xs text-muted-foreground">
            全部企业数量
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">启用企业</div>
            <Power className="w-5 h-5 text-green-500" />
          </div>
          <div className="text-3xl font-bold mb-1">{stats.active}</div>
          <div className="text-xs text-green-600">
            正常运营中
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">禁用企业</div>
            <PowerOff className="w-5 h-5 text-gray-500" />
          </div>
          <div className="text-3xl font-bold mb-1">{stats.inactive}</div>
          <div className="text-xs text-muted-foreground">
            已暂停使用
          </div>
        </Card>
      </div>

      {/* Enterprise List */}
      <Card className="p-6">
        <div className="flex items-center justify-between mb-4">
          <h3>企业列表</h3>
          <div className="flex gap-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={state.searchText}
                onChange={(e) => dispatch({ type: 'SET_SEARCH_TEXT', payload: e.target.value || '' })}
                className="pl-10 w-64"
              />
            </div>
            <Button onClick={handleAdd}>
              <Plus className="w-4 h-4 mr-2" />
              新建企业
            </Button>
          </div>
        </div>

        <div className="border rounded-lg overflow-hidden">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>企业编码</TableHead>
                <TableHead>企业名称</TableHead>
                <TableHead>企业类型</TableHead>
                <TableHead>联系人</TableHead>
                <TableHead>联系电话</TableHead>
                <TableHead>创建时间</TableHead>
                <TableHead>审核状态</TableHead>
                <TableHead>状态</TableHead>
                <TableHead>操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredEnterprises.map((enterprise) => (
                <TableRow key={enterprise.id}>
                  <TableCell className="font-medium">{enterprise.code}</TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <Building2 className="w-4 h-4 text-blue-500" />
                      <span className="font-medium">{enterprise.name}</span>
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline">{enterprise.type || '未分类'}</Badge>
                  </TableCell>
                  <TableCell>{enterprise.contact || '-'}</TableCell>
                  <TableCell>{enterprise.phone || '-'}</TableCell>
                  <TableCell className="text-sm">{enterprise.createdAt}</TableCell>
                  <TableCell>{getAuditStatusBadge(enterprise.auditStatus)}</TableCell>
                  <TableCell>{getStatusBadge(enterprise.status)}</TableCell>
                  <TableCell>
                    <div className="flex gap-2">
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => handleView(enterprise)}
                      >
                        <Eye className="w-3 h-3 mr-1" />
                        查看
                      </Button>
                      {enterprise.status === 'active' ? (
                        <Button
                          size="sm"
                          variant="outline"
                          className="text-gray-600 border-gray-300"
                          onClick={() => handleStatusChange(enterprise, 'disable')}
                        >
                          <PowerOff className="w-3 h-3 mr-1" />
                          禁用
                        </Button>
                      ) : (
                        <Button
                          size="sm"
                          variant="outline"
                          className="text-green-600 border-green-300"
                          onClick={() => handleStatusChange(enterprise, 'enable')}
                        >
                          <Power className="w-3 h-3 mr-1" />
                          启用
                        </Button>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>

        {filteredEnterprises.length === 0 && (
          <div className="text-center py-12 text-muted-foreground">
            <Building2 className="w-12 h-12 mx-auto mb-4 opacity-20" />
            <p>暂无企业数据</p>
          </div>
        )}
      </Card>

      {/* Add Enterprise Dialog */}
      <Dialog open={state.showAddDialog} onOpenChange={(open) => dispatch({ type: 'TOGGLE_ADD_DIALOG', payload: open })}>
        <DialogContent className="w-[80vw] max-w-4xl">
          <DialogHeader>
            <DialogTitle>新建企业</DialogTitle>
            <DialogDescription>
              创建新企业账号，管理员仅需填写基本信息，详细信息由企业登录后自行完善
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div>
              <Label>企业名称 *</Label>
              <div className="relative mt-2">
                <Building2 className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                <Input
                  placeholder="请输入企业全称"
                  value={state.formData.name}
                  onChange={(e) => updateFormData('name', e.target.value)}
                  className="pl-10"
                />
              </div>
            </div>

            <div>
              <Label>企业编码 *</Label>
              <div className="relative mt-2">
                <Hash className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                <Input
                  placeholder="请输入企业唯一编码，如：LYNY001"
                  value={state.formData.code}
                  onChange={(e) => updateFormData('code', e.target.value.toUpperCase())}
                  className="pl-10"
                />
              </div>
              <p className="text-xs text-muted-foreground mt-1">编码创建后不可修改，请谨慎填写</p>
            </div>

            <div>
              <Label>企业类型</Label>
              <div className="relative mt-2">
                <Building2 className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                <Input
                  placeholder="如：种植企业、养殖企业、合作社等"
                  value={state.formData.type}
                  onChange={(e) => updateFormData('type', e.target.value)}
                  className="pl-10"
                />
              </div>
            </div>

            <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
              <p className="text-sm text-blue-800">
                <strong>温馨提示：</strong>
              </p>
              <ul className="text-sm text-blue-700 mt-2 space-y-1">
                <li>• 企业创建后默认为启用状态，审核状态为"未提交"</li>
                <li>• 联系人、电话、地址等详细信息由企业登录后自行填写</li>
                <li>• 企业编码创建后不可修改，请确保准确无误</li>
              </ul>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => dispatch({ type: 'TOGGLE_ADD_DIALOG', payload: false })}>
              取消
            </Button>
            <Button onClick={confirmAdd}>创建企业</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* View Enterprise Details Dialog */}
      <Dialog open={state.showViewDialog} onOpenChange={(open) => dispatch({ type: 'TOGGLE_VIEW_DIALOG', payload: open })}>
        <DialogContent className="w-[80vw] max-w-6xl max-h-[90vh]">
          <DialogHeader>
            <div className="flex items-center justify-between pr-8">
              <DialogTitle>企业详情</DialogTitle>
              {state.selectedEnterprise && (
                <div className="flex gap-2">
                  {getAuditStatusBadge(state.selectedEnterprise.auditStatus)}
                  {getStatusBadge(state.selectedEnterprise.status)}
                </div>
              )}
            </div>
            <DialogDescription className="sr-only">
              查看企业的详细信息
            </DialogDescription>
          </DialogHeader>
          {state.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">
                    <Building2 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>

                {/* Basic Information */}
                <TabsContent value="basic" className="space-y-4">
                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <Label>企业名称</Label>
                      <div className="field-value p-2 bg-muted rounded">{state.selectedEnterprise.name}</div>
                    </div>
                    <div>
                      <Label>企业编码</Label>
                      <div className="field-value p-2 bg-muted rounded">{state.selectedEnterprise.code}</div>
                    </div>
                    <div>
                      <Label>企业类型</Label>
                      <div className="field-value p-2 bg-muted rounded">{state.selectedEnterprise.type || '-'}</div>
                    </div>
                    <div>
                      <Label>所在地区</Label>
                      <div className="field-value p-2 bg-muted rounded">
                        {state.selectedEnterprise.province || '-'} {state.selectedEnterprise.city || ''} {state.selectedEnterprise.district || ''}
                      </div>
                    </div>
                    <div className="col-span-2">
                      <Label>详细地址</Label>
                      <div className="field-value p-2 bg-muted rounded">{state.selectedEnterprise.address || '-'}</div>
                    </div>
                    <div>
                      <Label>登记人</Label>
                      <div className="field-value p-2 bg-muted rounded">{state.selectedEnterprise.registrant || '-'}</div>
                    </div>
                    <div>
                      <Label>联系电话</Label>
                      <div className="field-value p-2 bg-muted rounded">{state.selectedEnterprise.contactPhone || state.selectedEnterprise.phone || '-'}</div>
                    </div>
                  </div>
                </TabsContent>

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

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

                {/* Legal Person Information */}
                <TabsContent value="legal" className="space-y-4">
                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <Label>法人姓名</Label>
                      <div className="field-value p-2 bg-muted rounded">{state.selectedEnterprise.legalPerson || '-'}</div>
                    </div>
                    <div>
                      <Label>联系人</Label>
                      <div className="field-value p-2 bg-muted rounded">{state.selectedEnterprise.contact || '-'}</div>
                    </div>
                    <div className="col-span-2">
                      <Label>身份证正面</Label>
                      <div className="mt-2">
                        {state.selectedEnterprise.idCardFront ? (
                          <img
                            src={state.selectedEnterprise.idCardFront}
                            alt="身份证正面"
                            className="w-64 h-auto border rounded-lg"
                          />
                        ) : (
                          <span className="text-muted-foreground">未上传</span>
                        )}
                      </div>
                    </div>
                    <div className="col-span-2">
                      <Label>身份证反面</Label>
                      <div className="mt-2">
                        {state.selectedEnterprise.idCardBack ? (
                          <img
                            src={state.selectedEnterprise.idCardBack}
                            alt="身份证反面"
                            className="w-64 h-auto border rounded-lg"
                          />
                        ) : (
                          <span className="text-muted-foreground">未上传</span>
                        )}
                      </div>
                    </div>
                  </div>
                </TabsContent>
              </Tabs>
            </ScrollArea>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => dispatch({ type: 'TOGGLE_VIEW_DIALOG', payload: false })}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Status Change Confirmation Dialog */}
      <AlertDialog open={state.showStatusDialog} onOpenChange={(open) => dispatch({ type: 'TOGGLE_STATUS_DIALOG', payload: open })}>
        <AlertDialogContent className="w-[80vw] max-w-md">
          <AlertDialogHeader>
            <AlertDialogTitle>
              确认{state.statusAction === 'enable' ? '启用' : '禁用'}企业
            </AlertDialogTitle>
            <AlertDialogDescription>
              {state.statusAction === 'enable' ? (
                <>
                  启用企业 <strong>{state.selectedEnterprise?.name}</strong> 后，该企业用户将恢复正常登录和使用权限。
                </>
              ) : (
                <>
                  禁用企业 <strong>{state.selectedEnterprise?.name}</strong> 后，该企业所有用户将无法登录系统。此操作不会删除企业数据，可随时重新启用。
                </>
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmStatusChange}
              className={state.statusAction === 'enable' ? 'bg-green-600 hover:bg-green-700' : 'bg-gray-600 hover:bg-gray-700'}
            >
              确认{state.statusAction === 'enable' ? '启用' : '禁用'}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}