'use client';

import { useState, useEffect } from 'react';
import { toast } from 'sonner';
import { Card } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Building, FileText, CreditCard, User } from 'lucide-react';

import { EnterpriseInfoHeader } from './components/EnterpriseInfoHeader';
import { AuditStatusAlert } from './components/AuditStatusAlert';
import { BasicInfoForm } from './components/BasicInfoForm';
import { OtherInfoForm } from './components/OtherInfoForm';
import { BankInfoForm } from './components/BankInfoForm';
import { LegalInfoForm } from './components/LegalInfoForm';
import { SystemInfo } from './components/SystemInfo';
import { OperationTips } from './components/OperationTips';
import { Enterprise } from './types';

export default function EnterpriseInfoPage() {
  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('图片上传功能需要对接后端服务');
  };

  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">
      <EnterpriseInfoHeader
        isEditing={isEditing}
        onEdit={handleEdit}
        onCancel={handleCancel}
        onSave={handleSave}
      />

      {/* 审核状态提示 */}
      <AuditStatusAlert enterprise={enterprise} />

      {/* 分标签页展示信息 */}
      <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">
          <BasicInfoForm
            enterprise={enterprise}
            isEditing={isEditing}
            formData={formData}
            onFieldChange={handleChange}
          />
        </TabsContent>

        {/* 其他信息 */}
        <TabsContent value="other" className="space-y-4">
          <OtherInfoForm
            enterprise={enterprise}
            isEditing={isEditing}
            formData={formData}
            onFieldChange={handleChange}
            onImageUpload={handleImageUpload}
          />
        </TabsContent>

        {/* 开户信息 */}
        <TabsContent value="bank" className="space-y-4">
          <BankInfoForm
            enterprise={enterprise}
            isEditing={isEditing}
            formData={formData}
            onFieldChange={handleChange}
            onImageUpload={handleImageUpload}
          />
        </TabsContent>

        {/* 法人信息 */}
        <TabsContent value="legal" className="space-y-4">
          <LegalInfoForm
            enterprise={enterprise}
            isEditing={isEditing}
            formData={formData}
            onFieldChange={handleChange}
            onImageUpload={handleImageUpload}
          />
        </TabsContent>
      </Tabs>

      {/* 系统信息 */}
      <SystemInfo enterprise={enterprise} />

      {/* 操作提示 */}
      <OperationTips />
    </div>
  );
}