import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '../ui/alert-dialog';
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 { Building2, Plus, Eye, Power, PowerOff, Search, Hash, FileText, CreditCard, User } from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import { getAllEnterprises } from '../../lib/authStorage';
import type { Enterprise } from '../../types/auth';

export function EnterpriseManagement() {
  const [enterprises, setEnterprises] = useState<Enterprise[]>([]);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showViewDialog, setShowViewDialog] = useState(false);
  const [showStatusDialog, setShowStatusDialog] = useState(false);
  const [selectedEnterprise, setSelectedEnterprise] = useState<Enterprise | null>(null);
  const [searchText, setSearchText] = useState('');
  const [statusAction, setStatusAction] = useState<'enable' | 'disable'>('enable');

  // 表单数据
  const [formData, setFormData] = useState({
    name: '',
    code: '',
    type: '',
  });

  // 组件挂载时加载数据
  useEffect(() => {
    setEnterprises(getAllEnterprises());
  }, []);

  // 筛选企业
  const filteredEnterprises = enterprises.filter(ent => {
    if (!searchText) return true;
    return (
      ent.name.toLowerCase().includes(searchText.toLowerCase()) ||
      ent.code.toLowerCase().includes(searchText.toLowerCase()) ||
      (ent.type && ent.type.toLowerCase().includes(searchText.toLowerCase()))
    );
  });

  // 统计数据
  const stats = {
    total: enterprises.length,
    active: enterprises.filter(e => e.status === 'active').length,
    inactive: enterprises.filter(e => e.status === 'inactive').length,
  };

  const handleAdd = () => {
    setFormData({ name: '', code: '', type: '' });
    setShowAddDialog(true);
  };

  const handleView = (enterprise: Enterprise) => {
    setSelectedEnterprise(enterprise);
    setShowViewDialog(true);
  };

  const handleStatusChange = (enterprise: Enterprise, action: 'enable' | 'disable') => {
    setSelectedEnterprise(enterprise);
    setStatusAction(action);
    setShowStatusDialog(true);
  };

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

    // 检查编码是否重复
    if (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),
    };

    setEnterprises([...enterprises, newEnterprise]);
    setShowAddDialog(false);
    toast.success('企业创建成功');
  };

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

    const newStatus = statusAction === 'enable' ? 'active' : 'inactive';
    const updatedEnterprises = enterprises.map(ent =>
      ent.id === selectedEnterprise.id ? { ...ent, status: newStatus } : ent
    );

    setEnterprises(updatedEnterprises);
    setShowStatusDialog(false);
    toast.success(statusAction === 'enable' ? '企业已启用' : '企业已禁用');
  };

  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>;
    }
  };

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <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="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>

      {/* 统计卡片 */}
      <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>

      {/* 企业列表 */}
      <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-gray-400" />
              <Input
                placeholder="搜索企业名称、编码..."
                value={searchText}
                onChange={(e) => setSearchText(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>

      {/* 新建企业对话框 */}
      <Dialog open={showAddDialog} onOpenChange={setShowAddDialog}>
        <DialogContent>
          <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-gray-400" />
                <Input
                  placeholder="请输入企业全称"
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, 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-gray-400" />
                <Input
                  placeholder="请输入企业唯一编码，如：LYNY001"
                  value={formData.code}
                  onChange={(e) => setFormData({ ...formData, 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-gray-400" />
                <Input
                  placeholder="如：种植企业、养殖企业、合作社等"
                  value={formData.type}
                  onChange={(e) => setFormData({ ...formData, 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={() => setShowAddDialog(false)}>取消</Button>
            <Button onClick={confirmAdd}>创建企业</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 查看企业详情对话框 */}
      <Dialog open={showViewDialog} onOpenChange={setShowViewDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh]">
          <DialogHeader>
            <div className="flex items-center justify-between pr-8">
              <DialogTitle>企业详情</DialogTitle>
              {selectedEnterprise && (
                <div className="flex gap-2">
                  {getAuditStatusBadge(selectedEnterprise.auditStatus)}
                  {getStatusBadge(selectedEnterprise.status)}
                </div>
              )}
            </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">
                    <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>

                {/* 企业基本信息 */}
                <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.code}</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 className="col-span-2">
                      <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 || selectedEnterprise.phone || '-'}</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">
                        {selectedEnterprise.socialCreditCode ? (
                          <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-2 gap-6">
                    <div>
                      <Label>法人姓名</Label>
                      <div className="field-value">{selectedEnterprise.legalPerson || '-'}</div>
                    </div>
                    <div>
                      <Label>联系人</Label>
                      <div className="field-value">{selectedEnterprise.contact || '-'}</div>
                    </div>
                    <div className="col-span-2">
                      <Label>身份证正面</Label>
                      <div className="mt-2">
                        {selectedEnterprise.idCardFront ? (
                          <img
                            src={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">
                        {selectedEnterprise.idCardBack ? (
                          <img
                            src={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={() => setShowViewDialog(false)}>关闭</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 状态变更确认对话框 */}
      <AlertDialog open={showStatusDialog} onOpenChange={setShowStatusDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              确认{statusAction === 'enable' ? '启用' : '禁用'}企业
            </AlertDialogTitle>
            <AlertDialogDescription>
              {statusAction === 'enable' ? (
                <>
                  启用企业 <strong>{selectedEnterprise?.name}</strong> 后，该企业用户将恢复正常登录和使用权限。
                </>
              ) : (
                <>
                  禁用企业 <strong>{selectedEnterprise?.name}</strong> 后，该企业所有用户将无法登录系统。此操作不会删除企业数据，可随时重新启用。
                </>
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmStatusChange}
              className={statusAction === 'enable' ? 'bg-green-600 hover:bg-green-700' : 'bg-gray-600 hover:bg-gray-700'}
            >
              确认{statusAction === 'enable' ? '启用' : '禁用'}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
