"use client";

import { useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/common/dialog";
import { Button } from "@/components/common/button";
import { Upload, AlertCircle } from "lucide-react";
import { toast } from "sonner";
import { Alert, AlertDescription } from "@/components/common/alert";

interface ImportProductsModalProps {
  open: boolean;  
  setOpen: (open: boolean) => void;
  onImportComplete: () => void;
}

interface Price {
  quantity: number;
  unit: string;
  pricePerUnit: number;
  totalPrice: number;
}

// Add unit standardization mapping
const unitMatch: Record<string, string> = {
  "cart": "pcs",
  "gr": "gr",
  "pcs": "pcs",
  "unit": "pcs",
  "tip": "pcs",
  "bar": "pcs",
  "vape": "pcs",
  "ml": "pcs",
  "pill": "pcs",
};

export default function ImportProductsModal({ open, setOpen, onImportComplete }: ImportProductsModalProps) {
  const [file, setFile] = useState<File | null>(null);
  const [isUploading, setIsUploading] = useState(false);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0];
    if (selectedFile && selectedFile.type === "text/plain") {
      setFile(selectedFile);
    } else {
      toast.error("Please select a valid .txt file");
    }
  };

  const handleImport = async () => {
    if (!file) {
      toast.error("Please select a file first");
      return;
    }

    try {
      setIsUploading(true);
      const fileContent = await file.text();
      const sections = fileContent.split("----------------------------------------------------------");
      const processedProducts = [];

      for (const section of sections) {
        const productInfo = section.split("\n\n")[1];
        if (!productInfo) continue;

        const [name] = productInfo.split("\n");
        if (!name) continue;

        const [category, subcategory] = productInfo.split("\n")[1].split("•")[0].split("->")
          .map(item => item.trim());

        if (!category || !subcategory) continue;

        // Process pricing
        const priceText = section.split("\n\n")[2];
        if (!priceText) continue;

        const priceLines = priceText.trim().split("\n");
        const prices = priceLines
          .map(line => {
            const matches = line.match(/from (\d+\.?\d*) (cart[s]?|gr|grams?|g|pcs|unit[s]?|tip[s]?|bar[s]?|vape[s]?|ml|pill[s]?) @ £(\d+\.?\d*)/);
            if (!matches) return null;

            const quantity = parseFloat(matches[1]);
            const totalPrice = parseFloat(matches[3]);
            const pricePerUnit = totalPrice / quantity; 
            
            const rawUnit = matches[2].replace(/s$/, '');
            return {
              quantity,
              unit: unitMatch[rawUnit] || rawUnit,
              pricePerUnit,
              totalPrice
            };
          })
          .filter((price): price is Price => price !== null)
          .sort((a, b) => a.quantity - b.quantity);

        if (prices.length > 0) {
          processedProducts.push({ name, category, subcategory, prices });
        }
      }

      console.log('Processed products:', processedProducts);
      
      // Get auth token from cookie
      const authToken = document.cookie.split("Authorization=")[1];
      
      // Send to API
      const response = await fetch(`/api/products/batch`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify({ products: processedProducts })
      });

      if (!response.ok) {
        throw new Error('Failed to upload products');
      }

      toast.success(`Successfully imported ${processedProducts.length} products`);
      onImportComplete();
      setOpen(false);
    } catch (error) {
      toast.error("Failed to import products");
      console.error(error);
    } finally {
      setIsUploading(false);
      setFile(null);
    }
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Upload className="h-5 w-5" />
            Import Products
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          <Alert>
            <AlertCircle className="h-4 w-4" />
            <AlertDescription>
              File should be a .txt file with product details in the correct format
            </AlertDescription>
          </Alert>

          <div className="grid w-full items-center gap-1.5">
            <label 
              htmlFor="file-upload" 
              className="border-2 border-dashed rounded-lg p-8 text-center cursor-pointer hover:border-gray-400 transition-colors"
            >
              {file ? (
                <div className="text-sm text-muted-foreground">
                  Selected: {file.name}
                </div>
              ) : (
                <div className="text-sm text-muted-foreground">
                  Click to select or drag and drop a .txt file
                </div>
              )}
              <input
                id="file-upload"
                type="file"
                accept=".txt"
                onChange={handleFileChange}
                className="hidden"
              />
            </label>
          </div>
        </div>

        <DialogFooter className="sm:justify-start">
          <Button
            type="button"
            variant="secondary"
            onClick={() => setOpen(false)}
          >
            Cancel
          </Button>
          <Button
            type="button"
            onClick={handleImport}
            disabled={!file || isUploading}
          >
            {isUploading ? "Importing..." : "Import Products"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
} 
