import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Badge } from '../ui/badge';
import { Textarea } from '../ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Enterprise } from '../../types/user-management';
import { Edit, Save, X, Building, FileText, CreditCard, User, Upload, Image as ImageIcon } from 'lucide-react';
import { toast } from 'sonner@2.0.3';

export function EnterpriseInfo() {
  const [enterprise, setEnterprise] = useState<Enterprise | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  const [formData, setFormData] = useState<Partial<Enterprise>>({});

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

  const loadEnterpriseInfo = () => {
    const stored = localStorage.getItem('smart_agriculture_enterprise_info');
    if (stored) {
      const data = JSON.parse(stored);
      setEnterprise(data);
      setFormData(data);
    } else {
      // 初始化模拟数据
      const mockData: Enterprise = {
        id: 'ent-001',
        // 基本信息
        name: '智慧农业科技有限公司',
        type: '有限责任公司',
        province: '北京市',
        city: '海淀区',
        district: '中关村街道',
        
        // 其他信息
        companySize: '50-200人',
        registeredCapital: '1000万元',
        establishmentDate: '2020-01-15',
        invoiceType: '增值税专用发票',
        socialCreditCode: '91110108MA01XXXX00',
        businessScope: '农业技术开发、技术咨询、技术服务；销售机械设备、电子产品；软件开发；数据处理服务。',
        businessLicense: '',
        
        // 开户信息
        bankAccount: '1234567890123456789',
        bankName: '中国工商银行',
        bankFullName: '中国工商银行股份有限公司北京中关村支行',
        bankAddress: '北京市海淀区中关村大街1号',
        bankLicense: '',
        
        // 法人信息
        legalPerson: '张伟',
        idCardFront: '',
        idCardBack: '',
        
        // 联系信息
        registrant: '李明',
        contactPhone: '010-88888888',
        address: '北京市海淀区中关村大街1号科技大厦A座10层',
        
        // 系统信息
        status: 'active',
        auditStatus: 'approved',
        createdAt: '2024-01-15T00:00:00',
        updatedAt: '2024-01-15T00:00:00',
      };
      localStorage.setItem('smart_agriculture_enterprise_info', JSON.stringify(mockData));
      setEnterprise(mockData);
      setFormData(mockData);
    }
  };

  const handleEdit = () => {
    setIsEditing(true);
  };

  const handleCancel = () => {
    setIsEditing(false);
    if (enterprise) {
      setFormData(enterprise);
    }
  };

  const handleSave = () => {
    if (!formData.name || !formData.type || !formData.socialCreditCode) {
      toast.error('请填写必填项');
      return;
    }

    const updatedData: Enterprise = {
      ...(enterprise as Enterprise),
      ...formData,
      updatedAt: new Date().toISOString(),
      auditStatus: 'pending', // 修改后需要重新审核
    };

    localStorage.setItem('smart_agriculture_enterprise_info', JSON.stringify(updatedData));
    setEnterprise(updatedData);
    setFormData(updatedData);
    setIsEditing(false);
    toast.success('企业信息已更新，等待管理员审核');
  };

  const handleChange = (field: keyof Enterprise, value: any) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleImageUpload = (field: keyof Enterprise) => {
    // 模拟图片上传
    toast.success('图片上传功能需要对接后端服务');
  };

  const getAuditStatusBadge = (status: string) => {
    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>;
    }
  };

  if (!enterprise) {
    return (
      <div className="space-y-6">
        <div>
          <h2 className="text-green-800">企业信息</h2>
          <p className="text-muted-foreground">查看和管理本企业的完整注册信息</p>
        </div>
        <Card className="p-8 text-center text-muted-foreground">
          暂无企业信息
        </Card>
      </div>
    );
  }

  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>
        {!isEditing ? (
          <Button onClick={handleEdit}>
            <Edit className="w-4 h-4 mr-2" />
            编辑信息
          </Button>
        ) : (
          <div className="flex gap-2">
            <Button variant="outline" onClick={handleCancel}>
              <X className="w-4 h-4 mr-2" />
              取消
            </Button>
            <Button onClick={handleSave}>
              <Save className="w-4 h-4 mr-2" />
              提交审核
            </Button>
          </div>
        )}
      </div>

      {/* 审核状态提示 */}
      <Card className={`p-4 ${
        enterprise.auditStatus === 'pending' ? 'bg-yellow-50 border-yellow-200' :
        enterprise.auditStatus === 'rejected' ? 'bg-red-50 border-red-200' :
        'bg-green-50 border-green-200'
      }`}>
        <div className="flex items-center justify-between">
          <div>
            <div className="flex items-center gap-2">
              <span>当前审核状态：</span>
              {getAuditStatusBadge(enterprise.auditStatus)}
            </div>
            {enterprise.auditStatus === 'rejected' && enterprise.auditReason && (
              <p className="text-sm text-red-700 mt-2">
                驳回原因：{enterprise.auditReason}
              </p>
            )}
            {enterprise.auditStatus === 'pending' && (
              <p className="text-sm text-yellow-700 mt-2">
                信息修改后需要管理员重新审核
              </p>
            )}
          </div>
          {enterprise.auditTime && (
            <div className="text-sm text-muted-foreground">
              审核时间：{new Date(enterprise.auditTime).toLocaleString('zh-CN')}
            </div>
          )}
        </div>
      </Card>

      {/* 分标签页展示信息 */}
      <Tabs defaultValue="basic" className="space-y-4">
        <TabsList className="grid grid-cols-4 w-full max-w-2xl">
          <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">
          <Card className="p-6">
            <h3 className="mb-6 pb-4 border-b">企业基本信息</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <Label>企业名称 *</Label>
                {isEditing ? (
                  <Input
                    value={formData.name || ''}
                    onChange={(e) => handleChange('name', e.target.value)}
                    placeholder="请输入企业名称"
                    className="mt-2"
                  />
                ) : (
                  <div className="field-value">{enterprise.name}</div>
                )}
              </div>

              <div>
                <Label>企业类型 *</Label>
                {isEditing ? (
                  <Select
                    value={formData.type || ''}
                    onValueChange={(value) => handleChange('type', value)}
                  >
                    <SelectTrigger className="mt-2">
                      <SelectValue placeholder="选择企业类型" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="有限责任公司">有限责任公司</SelectItem>
                      <SelectItem value="股份有限公司">股份有限公司</SelectItem>
                      <SelectItem value="个人独资企业">个人独资企业</SelectItem>
                      <SelectItem value="合伙企业">合伙企业</SelectItem>
                      <SelectItem value="个体工商户">个体工商户</SelectItem>
                      <SelectItem value="农民专业合作社">农民专业合作社</SelectItem>
                    </SelectContent>
                  </Select>
                ) : (
                  <div className="field-value">{enterprise.type}</div>
                )}
              </div>

              <div>
                <Label>所在地区 *</Label>
                {isEditing ? (
                  <div className="grid grid-cols-2 gap-2 mt-2">
                    <Input
                      value={formData.province || ''}
                      onChange={(e) => handleChange('province', e.target.value)}
                      placeholder="省份"
                    />
                    <Input
                      value={formData.city || ''}
                      onChange={(e) => handleChange('city', e.target.value)}
                      placeholder="城市"
                    />
                  </div>
                ) : (
                  <div className="field-value">{enterprise.province} {enterprise.city}</div>
                )}
              </div>

              <div>
                <Label>详细地址 *</Label>
                {isEditing ? (
                  <Input
                    value={formData.address || ''}
                    onChange={(e) => handleChange('address', e.target.value)}
                    placeholder="请输入详细地址"
                    className="mt-2"
                  />
                ) : (
                  <div className="field-value">{enterprise.address}</div>
                )}
              </div>

              <div>
                <Label>登记人</Label>
                {isEditing ? (
                  <Input
                    value={formData.registrant || ''}
                    onChange={(e) => handleChange('registrant', e.target.value)}
                    placeholder="请输入登记人姓名"
                    className="mt-2"
                  />
                ) : (
                  <div className="field-value">{enterprise.registrant}</div>
                )}
              </div>

              <div>
                <Label>联系电话 *</Label>
                {isEditing ? (
                  <Input
                    value={formData.contactPhone || ''}
                    onChange={(e) => handleChange('contactPhone', e.target.value)}
                    placeholder="请输入联系电话"
                    className="mt-2"
                  />
                ) : (
                  <div className="field-value">{enterprise.contactPhone}</div>
                )}
              </div>
            </div>
          </Card>
        </TabsContent>

        {/* 其他信息 */}
        <TabsContent value="other" className="space-y-4">
          <Card className="p-6">
            <h3 className="mb-6 pb-4 border-b">其他信息</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <Label>公司规模</Label>
                {isEditing ? (
                  <Select
                    value={formData.companySize || ''}
                    onValueChange={(value) => handleChange('companySize', value)}
                  >
                    <SelectTrigger className="mt-2">
                      <SelectValue placeholder="选择公司规模" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="1-50人">1-50人</SelectItem>
                      <SelectItem value="50-200人">50-200人</SelectItem>
                      <SelectItem value="200-500人">200-500人</SelectItem>
                      <SelectItem value="500-1000人">500-1000人</SelectItem>
                      <SelectItem value="1000人以上">1000人以上</SelectItem>
                    </SelectContent>
                  </Select>
                ) : (
                  <div className="field-value">{enterprise.companySize || '-'}</div>
                )}
              </div>

              <div>
                <Label>注册资本</Label>
                {isEditing ? (
                  <Input
                    value={formData.registeredCapital || ''}
                    onChange={(e) => handleChange('registeredCapital', e.target.value)}
                    placeholder="如：1000万元"
                    className="mt-2"
                  />
                ) : (
                  <div className="field-value">{enterprise.registeredCapital || '-'}</div>
                )}
              </div>

              <div>
                <Label>成立时间</Label>
                {isEditing ? (
                  <Input
                    type="date"
                    value={formData.establishmentDate || ''}
                    onChange={(e) => handleChange('establishmentDate', e.target.value)}
                    className="mt-2"
                  />
                ) : (
                  <div className="field-value">{enterprise.establishmentDate || '-'}</div>
                )}
              </div>

              <div>
                <Label>发票类型</Label>
                {isEditing ? (
                  <Select
                    value={formData.invoiceType || ''}
                    onValueChange={(value) => handleChange('invoiceType', value)}
                  >
                    <SelectTrigger className="mt-2">
                      <SelectValue placeholder="选择发票类型" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="增值税专用发票">增值税专用发票</SelectItem>
                      <SelectItem value="增值税普通发票">增值税普通发票</SelectItem>
                      <SelectItem value="电子发票">电子发票</SelectItem>
                    </SelectContent>
                  </Select>
                ) : (
                  <div className="field-value">{enterprise.invoiceType || '-'}</div>
                )}
              </div>

              <div className="md:col-span-2">
                <Label>社会信用代码 *</Label>
                {isEditing ? (
                  <Input
                    value={formData.socialCreditCode || ''}
                    onChange={(e) => handleChange('socialCreditCode', e.target.value)}
                    placeholder="请输入18位社会信用代码"
                    className="mt-2"
                    maxLength={18}
                  />
                ) : (
                  <div className="field-value">
                    <code className="text-sm font-mono">
                      {enterprise.socialCreditCode}
                    </code>
                  </div>
                )}
              </div>

              <div className="md:col-span-2">
                <Label>经营范围</Label>
                {isEditing ? (
                  <Textarea
                    value={formData.businessScope || ''}
                    onChange={(e) => handleChange('businessScope', e.target.value)}
                    placeholder="请输入经营范围"
                    className="mt-2"
                    rows={4}
                  />
                ) : (
                  <div className="field-value">{enterprise.businessScope || '-'}</div>
                )}
              </div>

              <div className="md:col-span-2">
                <Label>营业执照</Label>
                <div className="mt-2">
                  {enterprise.businessLicense ? (
                    <div className="relative inline-block">
                      <img
                        src={enterprise.businessLicense}
                        alt="营业执照"
                        className="w-48 h-auto border rounded-lg"
                      />
                      {isEditing && (
                        <Button
                          size="sm"
                          variant="outline"
                          className="mt-2"
                          onClick={() => handleImageUpload('businessLicense')}
                        >
                          <Upload className="w-4 h-4 mr-2" />
                          重新上传
                        </Button>
                      )}
                    </div>
                  ) : (
                    isEditing ? (
                      <Button
                        variant="outline"
                        onClick={() => handleImageUpload('businessLicense')}
                      >
                        <Upload className="w-4 h-4 mr-2" />
                        上传营业执照
                      </Button>
                    ) : (
                      <span className="text-muted-foreground">未上传</span>
                    )
                  )}
                </div>
              </div>
            </div>
          </Card>
        </TabsContent>

        {/* 开户信息 */}
        <TabsContent value="bank" className="space-y-4">
          <Card className="p-6">
            <h3 className="mb-6 pb-4 border-b">开户信息</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <Label>银行账号</Label>
                {isEditing ? (
                  <Input
                    value={formData.bankAccount || ''}
                    onChange={(e) => handleChange('bankAccount', e.target.value)}
                    placeholder="请输入银行账号"
                    className="mt-2"
                  />
                ) : (
                  <div className="field-value">
                    {enterprise.bankAccount ? (
                      <code className="text-sm font-mono">
                        {enterprise.bankAccount}
                      </code>
                    ) : '-'}
                  </div>
                )}
              </div>

              <div>
                <Label>开户行</Label>
                {isEditing ? (
                  <Input
                    value={formData.bankName || ''}
                    onChange={(e) => handleChange('bankName', e.target.value)}
                    placeholder="如：中国工商银行"
                    className="mt-2"
                  />
                ) : (
                  <div className="field-value">{enterprise.bankName || '-'}</div>
                )}
              </div>

              <div className="md:col-span-2">
                <Label>开户行全称</Label>
                {isEditing ? (
                  <Input
                    value={formData.bankFullName || ''}
                    onChange={(e) => handleChange('bankFullName', e.target.value)}
                    placeholder="如：中国工商银行股份有限公司北京中关村支行"
                    className="mt-2"
                  />
                ) : (
                  <div className="field-value">{enterprise.bankFullName || '-'}</div>
                )}
              </div>

              <div className="md:col-span-2">
                <Label>开户行地址</Label>
                {isEditing ? (
                  <Input
                    value={formData.bankAddress || ''}
                    onChange={(e) => handleChange('bankAddress', e.target.value)}
                    placeholder="请输入开户行地址"
                    className="mt-2"
                  />
                ) : (
                  <div className="field-value">{enterprise.bankAddress || '-'}</div>
                )}
              </div>

              <div className="md:col-span-2">
                <Label>开户许可证</Label>
                <div className="mt-2">
                  {enterprise.bankLicense ? (
                    <div className="relative inline-block">
                      <img
                        src={enterprise.bankLicense}
                        alt="开户许可证"
                        className="w-48 h-auto border rounded-lg"
                      />
                      {isEditing && (
                        <Button
                          size="sm"
                          variant="outline"
                          className="mt-2"
                          onClick={() => handleImageUpload('bankLicense')}
                        >
                          <Upload className="w-4 h-4 mr-2" />
                          重新上传
                        </Button>
                      )}
                    </div>
                  ) : (
                    isEditing ? (
                      <Button
                        variant="outline"
                        onClick={() => handleImageUpload('bankLicense')}
                      >
                        <Upload className="w-4 h-4 mr-2" />
                        上传开户许可证
                      </Button>
                    ) : (
                      <span className="text-muted-foreground">未上传</span>
                    )
                  )}
                </div>
              </div>
            </div>
          </Card>
        </TabsContent>

        {/* 法人信息 */}
        <TabsContent value="legal" className="space-y-4">
          <Card className="p-6">
            <h3 className="mb-6 pb-4 border-b">法人信息</h3>
            <div className="grid grid-cols-1 gap-6">
              <div>
                <Label>法人名称</Label>
                {isEditing ? (
                  <Input
                    value={formData.legalPerson || ''}
                    onChange={(e) => handleChange('legalPerson', e.target.value)}
                    placeholder="请输入法人姓名"
                    className="mt-2"
                  />
                ) : (
                  <div className="field-value">{enterprise.legalPerson || '-'}</div>
                )}
              </div>

              <div>
                <Label>身份证正面</Label>
                <div className="mt-2">
                  {enterprise.idCardFront ? (
                    <div className="relative inline-block">
                      <img
                        src={enterprise.idCardFront}
                        alt="身份证正面"
                        className="w-64 h-auto border rounded-lg"
                      />
                      {isEditing && (
                        <Button
                          size="sm"
                          variant="outline"
                          className="mt-2"
                          onClick={() => handleImageUpload('idCardFront')}
                        >
                          <Upload className="w-4 h-4 mr-2" />
                          重新上传
                        </Button>
                      )}
                    </div>
                  ) : (
                    isEditing ? (
                      <Button
                        variant="outline"
                        onClick={() => handleImageUpload('idCardFront')}
                      >
                        <ImageIcon className="w-4 h-4 mr-2" />
                        上传身份证正面
                      </Button>
                    ) : (
                      <span className="text-muted-foreground">未上传</span>
                    )
                  )}
                </div>
              </div>

              <div>
                <Label>身份证反面</Label>
                <div className="mt-2">
                  {enterprise.idCardBack ? (
                    <div className="relative inline-block">
                      <img
                        src={enterprise.idCardBack}
                        alt="身份证反面"
                        className="w-64 h-auto border rounded-lg"
                      />
                      {isEditing && (
                        <Button
                          size="sm"
                          variant="outline"
                          className="mt-2"
                          onClick={() => handleImageUpload('idCardBack')}
                        >
                          <Upload className="w-4 h-4 mr-2" />
                          重新上传
                        </Button>
                      )}
                    </div>
                  ) : (
                    isEditing ? (
                      <Button
                        variant="outline"
                        onClick={() => handleImageUpload('idCardBack')}
                      >
                        <ImageIcon className="w-4 h-4 mr-2" />
                        上传身份证反面
                      </Button>
                    ) : (
                      <span className="text-muted-foreground">未上传</span>
                    )
                  )}
                </div>
              </div>
            </div>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 系统信息 */}
      <Card className="p-6">
        <h3 className="mb-6 pb-4 border-b">系统信息</h3>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
          <div>
            <Label>企业ID</Label>
            <div className="field-value">
              <code className="text-xs font-mono">{enterprise.id}</code>
            </div>
          </div>
          <div>
            <Label>注册时间</Label>
            <div className="field-value">
              {new Date(enterprise.createdAt).toLocaleString('zh-CN')}
            </div>
          </div>
          <div>
            <Label>最后更新</Label>
            <div className="field-value">
              {new Date(enterprise.updatedAt).toLocaleString('zh-CN')}
            </div>
          </div>
          {enterprise.auditor && (
            <div>
              <Label>审核人</Label>
              <div className="field-value">{enterprise.auditor}</div>
            </div>
          )}
        </div>
      </Card>

      {/* 操作提示 */}
      <Card className="p-4 bg-blue-50 border-blue-200">
        <h4 className="text-blue-900 mb-2">
          <FileText className="w-4 h-4 inline mr-2" />
          温馨提示
        </h4>
        <ul className="space-y-1 text-sm text-blue-800">
          <li>• 企业信息修改后需要提交至超级管理员重新审核</li>
          <li>• 请确保填写的信息真实准确，与营业执照等证件保持一致</li>
          <li>• 社会信用代码为18位，请仔细核对</li>
          <li>• 图片上传功能需要对接后端服务，目前仅为演示</li>
          <li>• 如有疑问，请联系系统管理员</li>
        </ul>
      </Card>
    </div>
  );
}
