import { useState, useEffect } from 'react';
import { Button } from '../ui/button';
import { Plus } from 'lucide-react';
import { MachineryRecord, MachineryChangeHistory, MachineryTag } from '../../types/machinery';
import { machineryStorage } from '../../lib/machineryStorage';
import { initializeMockData } from '../../lib/mockData';
import { initializeMaterialData } from '../../lib/materialStorage';
import { trackMachineryChanges } from '../../lib/changeTracker';
import { MachineryList } from './MachineryList';
import { MachineryForm } from './MachineryForm';
import { MachineryDetails } from './MachineryDetails';
import { QRCodeDialog } from './QRCodeDialog';
import { toast } from 'sonner@2.0.3';

export function MachineryArchive() {
  const [machinery, setMachinery] = useState<MachineryRecord[]>([]);
  const [tags, setTags] = useState<MachineryTag[]>([]);
  const [histories, setHistories] = useState<MachineryChangeHistory[]>([]);
  
  const [showForm, setShowForm] = useState(false);
  const [showDetails, setShowDetails] = useState(false);
  const [showQRCode, setShowQRCode] = useState(false);
  
  const [editingMachinery, setEditingMachinery] = useState<MachineryRecord | undefined>();
  const [selectedMachinery, setSelectedMachinery] = useState<MachineryRecord | null>(null);

  // 加载数据
  useEffect(() => {
    initializeMockData();
    initializeMaterialData();
    loadData();
  }, []);

  const loadData = () => {
    setMachinery(machineryStorage.getAllMachinery());
    setTags(machineryStorage.getAllTags());
  };



  // 保存农机档案
  const handleSaveMachinery = (data: Partial<MachineryRecord>) => {
    const currentUser = '系统管理员'; // 从 AuthContext 获取当前用户
    const now = new Date().toISOString();

    if (editingMachinery) {
      // 编辑现有农机
      const updatedMachinery: MachineryRecord = {
        ...editingMachinery,
        ...data,
        updatedAt: now,
        updatedBy: currentUser,
      };

      // 使用变更追踪工具自动记录所有变更
      const changes = trackMachineryChanges(editingMachinery, data, currentUser);
      
      // 保存所有变更记录
      changes.forEach(change => {
        machineryStorage.saveChangeHistory(change);
      });

      machineryStorage.saveMachinery(updatedMachinery);
      toast.success(`农机档案更新成功${changes.length > 0 ? `，记录了${changes.length}项变更` : ''}`);
    } else {
      const newMachinery: MachineryRecord = {
        id: `machinery-${Date.now()}`,
        name: data.name!,
        model: data.model!,
        category: data.category!,
        usage: data.usage!,
        manufacturer: data.manufacturer || '',
        manufactureDate: data.manufactureDate || '',
        purchaseDate: data.purchaseDate || '',
        engineNumber: data.engineNumber!,
        chassisNumber: data.chassisNumber!,
        power: data.power || '',
        weight: data.weight || '',
        workingWidth: data.workingWidth || '',
        purchasePrice: data.purchasePrice || 0,
        supplier: data.supplier || '',
        invoiceNumber: data.invoiceNumber || '',
        invoiceUrl: data.invoiceUrl,
        insuranceCompany: data.insuranceCompany,
        insurancePolicyNumber: data.insurancePolicyNumber,
        insuranceStartDate: data.insuranceStartDate,
        insuranceEndDate: data.insuranceEndDate,
        insuranceAmount: data.insuranceAmount,
        status: data.status!,
        currentLocation: data.currentLocation,
        operator: data.operator,
        department: data.department,
        remarks: data.remarks,
        tags: data.tags || [],
        qrCode: `machinery-${Date.now()}`,
        createdAt: now,
        updatedAt: now,
        createdBy: currentUser,
        updatedBy: currentUser,
      };

      machineryStorage.saveMachinery(newMachinery);
      toast.success('农机档案新增成功');
    }

    loadData();
    setShowForm(false);
    setEditingMachinery(undefined);
  };

  const handleDeleteMachinery = (id: string) => {
    machineryStorage.deleteMachinery(id);
    loadData();
    toast.success('农机档案删除成功');
  };

  const handleViewDetails = (m: MachineryRecord) => {
    setSelectedMachinery(m);
    setHistories(machineryStorage.getChangeHistory(m.id));
    setShowDetails(true);
  };

  const handleViewQRCode = (m: MachineryRecord) => {
    setSelectedMachinery(m);
    setShowQRCode(true);
  };

  const handleEdit = (m: MachineryRecord) => {
    setEditingMachinery(m);
    setShowForm(true);
  };

  const handleAdd = () => {
    setEditingMachinery(undefined);
    setShowForm(true);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-success">农机档案管理</h2>
          <p className="text-muted-foreground">农机设备档案录入与维护</p>
        </div>
        <Button className="bg-success hover:bg-success/90" onClick={handleAdd}>
          <Plus className="w-4 h-4 mr-2" />
          新增农机
        </Button>
      </div>

      <MachineryList
        machinery={machinery}
        tags={tags}
        onEdit={handleEdit}
        onDelete={handleDeleteMachinery}
        onViewQRCode={handleViewQRCode}
        onViewDetails={handleViewDetails}
      />

      <MachineryForm
        open={showForm}
        onClose={() => {
          setShowForm(false);
          setEditingMachinery(undefined);
        }}
        onSave={handleSaveMachinery}
        initialData={editingMachinery}
        availableTags={tags}
      />

      <MachineryDetails
        open={showDetails}
        onClose={() => {
          setShowDetails(false);
          setSelectedMachinery(null);
        }}
        machinery={selectedMachinery}
        history={histories}
        tags={tags}
      />

      <QRCodeDialog
        open={showQRCode}
        onClose={() => {
          setShowQRCode(false);
          setSelectedMachinery(null);
        }}
        machinery={selectedMachinery}
      />
    </div>
  );
}
