import { useState, useEffect } from 'react';
import { Button } from '../../ui/button';
import { Card } from '../../ui/card';
import { Input } from '../../ui/input';
import { MachineryRecord } from '../../../types/machinery';
import { machineryStorage } from '../../../lib/machineryStorage';
import { QRCodeDialog } from '../QRCodeDialog';
import { QrCode, Search, Printer } from 'lucide-react';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../../ui/table';

export function MachineryQRCode() {
  const [machinery, setMachinery] = useState<MachineryRecord[]>([]);
  const [filteredMachinery, setFilteredMachinery] = useState<MachineryRecord[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [selectedMachinery, setSelectedMachinery] = useState<MachineryRecord | null>(null);
  const [showQRCode, setShowQRCode] = useState(false);

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

  useEffect(() => {
    if (searchKeyword) {
      const filtered = machinery.filter(m => 
        m.name.toLowerCase().includes(searchKeyword.toLowerCase()) ||
        m.model.toLowerCase().includes(searchKeyword.toLowerCase()) ||
        m.engineNumber.toLowerCase().includes(searchKeyword.toLowerCase())
      );
      setFilteredMachinery(filtered);
    } else {
      setFilteredMachinery(machinery);
    }
  }, [searchKeyword, machinery]);

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

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

  // 批量打印二维码
  const handleBatchPrint = () => {
    const printWindow = window.open('', '_blank');
    if (printWindow) {
      const machineryList = filteredMachinery.length > 0 ? filteredMachinery : machinery;
      
      printWindow.document.write(`
        <html>
          <head>
            <title>批量打印农机二维码</title>
            <style>
              body {
                font-family: sans-serif;
              }
              .qrcode-grid {
                display: grid;
                grid-template-columns: repeat(3, 1fr);
                gap: 20px;
                padding: 20px;
              }
              .qrcode-item {
                border: 1px solid #ccc;
                padding: 15px;
                text-align: center;
                page-break-inside: avoid;
              }
              .qrcode-item h3 {
                margin: 10px 0 5px 0;
                font-size: 14px;
              }
              .qrcode-item p {
                margin: 3px 0;
                font-size: 12px;
                color: #666;
              }
              @media print {
                .qrcode-grid {
                  grid-template-columns: repeat(2, 1fr);
                }
              }
            </style>
          </head>
          <body>
            <div class="qrcode-grid">
              ${machineryList.map(m => `
                <div class="qrcode-item">
                  <canvas id="qr-${m.id}" width="200" height="200"></canvas>
                  <h3>${m.name}</h3>
                  <p>型号: ${m.model}</p>
                  <p>发动机号: ${m.engineNumber}</p>
                </div>
              `).join('')}
            </div>
            <script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.3/build/qrcode.min.js"></script>
            <script>
              window.onload = function() {
                ${machineryList.map(m => `
                  QRCode.toCanvas(document.getElementById('qr-${m.id}'), '${m.qrCode}', {
                    width: 200,
                    margin: 2
                  });
                `).join('\n')}
                
                setTimeout(() => {
                  window.print();
                }, 1000);
              }
            </script>
          </body>
        </html>
      `);
      printWindow.document.close();
    }
  };

  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={handleBatchPrint}>
          <Printer className="w-4 h-4 mr-2" />
          批量打印
        </Button>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">总二维码数</div>
          <div className="mt-1">{machinery.length}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">筛选结果</div>
          <div className="mt-1">{filteredMachinery.length}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">待打印</div>
          <div className="mt-1">{filteredMachinery.length || machinery.length}</div>
        </Card>
      </div>

      {/* 搜索栏 */}
      <Card className="p-4">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
          <Input
            placeholder="搜索设备名称、型号、发动机号..."
            value={searchKeyword}
            onChange={(e) => setSearchKeyword(e.target.value)}
            className="pl-9"
          />
        </div>
      </Card>

      {/* 二维码列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>设备名称</TableHead>
              <TableHead>型号</TableHead>
              <TableHead>发动机号</TableHead>
              <TableHead>车架号</TableHead>
              <TableHead>二维码内容</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredMachinery.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center text-muted-foreground py-8">
                  {searchKeyword ? '未找到匹配的设备' : '暂无数据'}
                </TableCell>
              </TableRow>
            ) : (
              filteredMachinery.map((item) => (
                <TableRow key={item.id}>
                  <TableCell>{item.name}</TableCell>
                  <TableCell>{item.model}</TableCell>
                  <TableCell>{item.engineNumber}</TableCell>
                  <TableCell>{item.chassisNumber}</TableCell>
                  <TableCell>
                    <code className="text-xs bg-muted px-2 py-1 rounded">
                      {item.qrCode}
                    </code>
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-2">
                      <Button 
                        variant="ghost" 
                        size="sm"
                        onClick={() => handleViewQRCode(item)}
                      >
                        <QrCode className="w-4 h-4" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>

      {/* 使用说明 */}
      <Card className="p-6 bg-info-muted border-info">
        <h4 className="mb-3 text-muted-foreground">使用说明</h4>
        <ul className="space-y-2 text-sm text-muted-foreground">
          <li>• 点击"查看"按钮可以预览和下载单个农机的二维码</li>
          <li>• 点击"批量打印"可以打印当前筛选结果的所有二维码</li>
          <li>• 每台农机的二维码包含唯一的设备标识信息</li>
          <li>• 建议将二维码打印并粘贴在对应的农机设备上</li>
        </ul>
      </Card>

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