import { useEffect, useState, useRef } from "react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "./ui/dialog";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "./ui/select";
import { toast } from "sonner@2.0.3";
import { RefreshCw, Download, Printer } from "lucide-react";
import BarcodeDisplay from "./BarcodeDisplay";
import type { Product, ProductType, ProductUnit } from "./ProductManagement";

interface ProductDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  product: Product | null;
  onSave: (product: Omit<Product, "id" | "createdAt" | "product_code">) => void;
}

export default function ProductDialog({
  open,
  onOpenChange,
  product,
  onSave,
}: ProductDialogProps) {
  const [formData, setFormData] = useState({
    name: "",
    type: "raw_material" as ProductType,
    unit: "kg" as ProductUnit,
    barcode_value: "",
  });

  const barcodeCanvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    if (product) {
      setFormData({
        name: product.name,
        type: product.type,
        unit: product.unit,
        barcode_value: product.barcode_value,
      });
    } else {
      setFormData({
        name: "",
        type: "raw_material",
        unit: "kg",
        barcode_value: "",
      });
    }
  }, [product, open]);

  const handleRegenerateBarcode = () => {
    if (product) {
      // 編輯模式：使用現有的商品編號
      setFormData({ ...formData, barcode_value: product.product_code });
      toast.success("條碼已重新生成");
    } else {
      // 新增模式：提示用戶條碼將在保存後自動生成
      const codeFormat = formData.type === "raw_material" ? "RMXXXX" : "SFXXXX";
      toast.info(`條碼將在儲存商品後自動生成（格式：${codeFormat}）`);
    }
  };

  const handleDownloadBarcode = () => {
    const canvas = document.querySelector(
      ".barcode-preview canvas"
    ) as HTMLCanvasElement;
    if (canvas) {
      const url = canvas.toDataURL("image/png");
      const link = document.createElement("a");
      link.download = `barcode-${formData.barcode_value || "preview"}.png`;
      link.href = url;
      link.click();
      toast.success("條碼圖片已下載");
    }
  };

  const handlePrintBarcode = () => {
    const canvas = document.querySelector(
      ".barcode-preview canvas"
    ) as HTMLCanvasElement;
    if (canvas) {
      const printWindow = window.open("", "_blank");
      if (printWindow) {
        printWindow.document.write(`
          <html>
            <head>
              <title>列印條碼 - ${formData.barcode_value || product?.product_code || ""}</title>
              <style>
                body {
                  margin: 0;
                  padding: 20px;
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                  justify-content: center;
                }
                img {
                  max-width: 100%;
                  height: auto;
                }
                .product-info {
                  margin-top: 10px;
                  text-align: center;
                  font-family: Arial, sans-serif;
                }
                @media print {
                  body {
                    padding: 0;
                  }
                }
              </style>
            </head>
            <body>
              <img src="${canvas.toDataURL("image/png")}" alt="Barcode" />
              <div class="product-info">
                <p><strong>商品名稱：</strong>${formData.name || ""}</p>
                <p><strong>商品編號：</strong>${product?.product_code || "待生成"}</p>
              </div>
              <script>
                window.onload = function() {
                  window.print();
                  window.onafterprint = function() {
                    window.close();
                  };
                };
              </script>
            </body>
          </html>
        `);
        printWindow.document.close();
      }
      toast.success("正在準備列印...");
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    if (!formData.name.trim()) {
      toast.error("請輸入商品名稱");
      return;
    }

    onSave(formData);
    toast.success(product ? "商品更新成功" : "商品新增成功");
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{product ? "編輯商品" : "新增商品"}</DialogTitle>
          <DialogDescription>
            {product ? "修改商品資料" : "建立新的商品資料"}
          </DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit}>
          <div className="grid gap-6 py-4">
            {/* Product Code Display (Read-only) */}
            {product && (
              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <div className="flex items-center justify-between">
                  <div>
                    <Label className="text-blue-900">商品編號</Label>
                    <p className="text-lg font-mono mt-1 text-blue-700">
                      {product.product_code}
                    </p>
                    <p className="text-xs text-blue-600 mt-1">
                      系統自動生成，不可修改
                    </p>
                  </div>
                </div>
              </div>
            )}

            {/* Product Code Info (Add mode) */}
            {!product && (
              <div className="bg-green-50 border border-green-200 rounded-lg p-4">
                <div className="flex items-start gap-3">
                  <div className="flex-1">
                    <Label className="text-green-900">商品編號生成規則</Label>
                    <p className="text-sm text-green-700 mt-1">
                      系統將根據商品類型自動生成編號：
                    </p>
                    <ul className="text-sm text-green-600 mt-2 space-y-1 ml-4 list-disc">
                      <li><span className="font-mono">原物料：RM + 4位數字</span> (例：RM0019)</li>
                      <li><span className="font-mono">半成品：SF + 4位數字</span> (例：SF0008)</li>
                    </ul>
                  </div>
                </div>
              </div>
            )}

            {/* Row 1: Name and Type */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="name">
                  商品名稱 <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="name"
                  value={formData.name}
                  onChange={(e) =>
                    setFormData({ ...formData, name: e.target.value })
                  }
                  placeholder="例：法國麵粉、草莓蛋糕"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="type">
                  類型 <span className="text-red-500">*</span>
                </Label>
                <Select
                  value={formData.type}
                  onValueChange={(value: ProductType) =>
                    setFormData({ ...formData, type: value })
                  }
                >
                  <SelectTrigger id="type">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="raw_material">原物料</SelectItem>
                    <SelectItem value="finished_product">半成品</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Row 2: Unit */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="unit">
                  單位 <span className="text-red-500">*</span>
                </Label>
                <Select
                  value={formData.unit}
                  onValueChange={(value: ProductUnit) =>
                    setFormData({ ...formData, unit: value })
                  }
                >
                  <SelectTrigger id="unit">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="kg">公斤 (kg)</SelectItem>
                    <SelectItem value="g">公克 (g)</SelectItem>
                    <SelectItem value="l">公升 (l)</SelectItem>
                    <SelectItem value="ml">毫升 (ml)</SelectItem>
                    <SelectItem value="piece">個</SelectItem>
                    <SelectItem value="box">盒/箱 (box)</SelectItem>
                    <SelectItem value="pack">包 (pack)</SelectItem>
                    <SelectItem value="bottle">瓶 (bottle)</SelectItem>
                    <SelectItem value="can">罐 (can)</SelectItem>
                    <SelectItem value="jar">瓶罐 (jar)</SelectItem>
                    <SelectItem value="bag">袋 (bag)</SelectItem>
                    <SelectItem value="basin">盆 (basin)</SelectItem>
                    <SelectItem value="container">容器 (container)</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Barcode Section */}
            <div className="border-t pt-6">
              <div className="bg-gradient-to-r from-purple-50 to-blue-50 border border-purple-200 rounded-lg p-6">
                <h3 className="mb-4 text-purple-900">條碼資訊</h3>

                {/* Barcode Value Display */}
                <div className="space-y-2 mb-4">
                  <Label>條碼內容</Label>
                  <Input
                    value={
                      formData.barcode_value ||
                      product?.product_code ||
                      "儲存後自動生成"
                    }
                    readOnly
                    className="font-mono bg-white"
                  />
                </div>

                {/* Barcode Preview */}
                <div className="space-y-2">
                  <Label>條���預覽</Label>
                  <div className="bg-white rounded-lg border-2 border-dashed border-purple-300 p-6 flex items-center justify-center barcode-preview">
                    {formData.barcode_value || product?.product_code ? (
                      <BarcodeDisplay
                        value={
                          formData.barcode_value || product?.product_code || ""
                        }
                        width={2}
                        height={60}
                        displayValue={true}
                      />
                    ) : (
                      <div className="text-center py-8">
                        <p className="text-gray-400">條碼將在儲存後顯示</p>
                      </div>
                    )}
                  </div>

                  {/* Barcode Action Buttons */}
                  {(formData.barcode_value || product?.product_code) && (
                    <div className="flex gap-2 mt-4">
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={handleDownloadBarcode}
                        className="button-outlined-primary flex-1"
                      >
                        <Download className="h-4 w-4 mr-2" />
                        下載條碼圖片
                      </Button>
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={handlePrintBarcode}
                        className="button-outlined-primary flex-1"
                      >
                        <Printer className="h-4 w-4 mr-2" />
                        列印條碼標籤
                      </Button>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              className="button-outlined-primary"
            >
              取消
            </Button>
            <Button type="submit" className="button-filled-primary">
              {product ? "儲存變更" : "新增商品"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}