import { useState, useEffect } from 'react';
import { Button } from '../../ui/button';
import { Plus, Tractor, CheckCircle, Wrench, XCircle } 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 { Card } from '../../ui/card';
import { toast } from 'sonner@2.0.3';

export function MachineryEntry() {
  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 [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 = '系统管理员';
    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 handleEdit = (m: MachineryRecord) => {
    setEditingMachinery(m);
    setShowForm(true);
  };

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

  // 计算统计数据
  const stats = {
    total: machinery.length,
    normal: machinery.filter(m => m.status === '正常').length,
    maintenance: machinery.filter(m => m.status === '待维护').length,
    scrapped: machinery.filter(m => m.status === '已报废').length,
  };

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

      {/* 数据统计卡片 */}
      <div className="grid grid-cols-4 gap-4">
        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">总数</p>
              <p className="text-2xl mt-1">{stats.total}</p>
            </div>
            <div className="w-12 h-12 bg-info-muted rounded-lg flex items-center justify-center">
              <Tractor className="w-6 h-6 text-info" />
            </div>
          </div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">正常</p>
              <p className="text-2xl mt-1">{stats.normal}</p>
            </div>
            <div className="w-12 h-12 bg-success-muted rounded-lg flex items-center justify-center">
              <CheckCircle className="w-6 h-6 text-success" />
            </div>
          </div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">待维护</p>
              <p className="text-2xl mt-1">{stats.maintenance}</p>
            </div>
            <div className="w-12 h-12 bg-warning-muted rounded-lg flex items-center justify-center">
              <Wrench className="w-6 h-6 text-warning" />
            </div>
          </div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">已报废</p>
              <p className="text-2xl mt-1">{stats.scrapped}</p>
            </div>
            <div className="w-12 h-12 bg-error-muted rounded-lg flex items-center justify-center">
              <XCircle className="w-6 h-6 text-error" />
            </div>
          </div>
        </Card>
      </div>

      <MachineryList
        machinery={machinery}
        tags={tags}
        onEdit={handleEdit}
        onDelete={handleDeleteMachinery}
        onViewQRCode={() => {}}
        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}
      />
    </div>
  );
}
