import { useState } from "react";
import { ReactSpreadsheetImport, ErrorLevel, StepType } from "@/components/product-import";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Code } from "@/components/ui/code";
import { toast } from "sonner";
import { motion } from "framer-motion";
import { useQuery } from "@tanstack/react-query";
import config from "@/config";
import { Loader2 } from "lucide-react";
// Define base fields without dynamic options
const BASE_IMPORT_FIELDS = [
  {
    label: "Supplier",
    key: "supplier",
    description: "Primary supplier/manufacturer of the product",
    fieldType: {
      type: "select" as const,
      options: [], // Will be populated from API
    },
    width: 220,
    validations: [{ rule: "required" as const, errorMessage: "Required", level: "error" as ErrorLevel }],
  },
  {
    label: "Company",
    key: "company",
    description: "Company/Brand name",
    fieldType: {
      type: "select",
      options: [], // Will be populated from API
    },
    width: 220,
    validations: [{ rule: "required", errorMessage: "Required", level: "error" }],
  },
  {
    label: "Line",
    key: "line",
    description: "Product line",
    alternateMatches: ["collection"],
    fieldType: {
      type: "select" as const,
      options: [], // Will be populated dynamically based on company selection
    },
    width: 220,
    validations: [{ rule: "required", errorMessage: "Required", level: "error" }],
  },
  {
    label: "Sub Line",
    key: "subline",
    description: "Product sub-line",
    fieldType: {
      type: "select" as const,
      options: [], // Will be populated dynamically based on line selection
    },
    width: 220,
  },
  {
    label: "UPC",
    key: "upc",
    description: "Universal Product Code/Barcode",
    alternateMatches: ["barcode", "bar code", "jan", "ean", "upc code"],
    fieldType: { type: "input" },
    width: 145,
    validations: [
      { rule: "required", errorMessage: "Required", level: "error" },
      { rule: "unique", errorMessage: "Must be unique", level: "error" },
      { rule: "regex", value: "^[0-9]+$", errorMessage: "Must be a number", level: "error" },
    ],
  },
  {
    label: "Item Number",
    key: "item_number",
    description: "Internal item reference number",
    fieldType: { type: "input" },
    width: 130,
    validations: [
      { rule: "required", errorMessage: "Required", level: "error" },
      { rule: "unique", errorMessage: "Must be unique", level: "error" },
    ],
  },
  {
    label: "Supplier #",
    key: "supplier_no",
    description: "Supplier's product identifier",
    alternateMatches: ["sku", "item#", "mfg item #", "item", "supplier #"],
    fieldType: { type: "input" },
    width: 130,
    validations: [
      { rule: "required", errorMessage: "Required", level: "error" },
      { rule: "unique", errorMessage: "Must be unique", level: "error" },
    ],
  },
  {
    label: "Notions #",
    key: "notions_no",
    description: "Internal notions number",
    alternateMatches: ["notions #","nmc"],
    fieldType: { type: "input" },
    width: 100,
    validations: [
      { rule: "required", errorMessage: "Required", level: "error" },
      { rule: "unique", errorMessage: "Must be unique", level: "error" },
      { rule: "regex", value: "^[0-9]+$", errorMessage: "Must be a number", level: "error" },
    ],
  },
  {
    label: "Name",
    key: "name",
    description: "Product name/title",
    alternateMatches: ["sku description","product name"],
    fieldType: { type: "input" },
    width: 500,
    validations: [
      { rule: "required", errorMessage: "Required", level: "error" },
      { rule: "unique", errorMessage: "Must be unique", level: "error" },
    ],
  },
  {
    label: "MSRP",
    key: "msrp",
    description: "Manufacturer's Suggested Retail Price",
    alternateMatches: ["retail", "retail price", "sugg retail", "price", "sugg. retail","default price"],
    fieldType: { 
      type: "input",
      price: true 
    },
    width: 100,
    validations: [
      { rule: "required", errorMessage: "Required", level: "error" },
      { rule: "regex", value: "^[0-9]*.?[0-9]+$", errorMessage: "Must be a number", level: "error" },
    ],
  },
  {
    label: "Min Qty",
    key: "qty_per_unit",
    description: "Quantity of items per individual unit",
    alternateMatches: ["inner pack", "inner", "min qty", "unit qty", "min. order qty", "supplier qty/unit"],
    fieldType: { type: "input" },
    width: 80,
    validations: [
      { rule: "required", errorMessage: "Required", level: "error" },
      { rule: "regex", value: "^[0-9]+$", errorMessage: "Must be a number", level: "error" },
    ],
  },
  {
    label: "Cost Each",
    key: "cost_each",
    description: "Wholesale cost per unit",
    alternateMatches: ["wholesale", "wholesale price", "supplier cost each"],
    fieldType: { 
      type: "input",
      price: true 
    },
    width: 100,
    validations: [
      { rule: "required", errorMessage: "Required", level: "error" },
      { rule: "regex", value: "^[0-9]*.?[0-9]+$", errorMessage: "Must be a number", level: "error" },
    ],
  },
  {
    label: "Case Pack",
    key: "case_qty",
    description: "Number of units per case",
    alternateMatches: ["mc qty","case qty","case pack","box ct"],
    fieldType: { type: "input" },
    width: 100,
    validations: [
      { rule: "regex", value: "^[0-9]+$", errorMessage: "Must be a number", level: "error" },
    ],
  },
  {
    label: "Tax Category",
    key: "tax_cat",
    description: "Product tax category",
    fieldType: {
      type: "select",
      options: [], // Will be populated from API
    },
    width: 200,
    validations: [{ rule: "required", errorMessage: "Required", level: "error" }],
  },
  {
    label: "Artist",
    key: "artist",
    description: "Artist/Designer name",
    fieldType: {
      type: "select",
      options: [], // Will be populated from API
    },
    width: 200,
  },
  {
    label: "ETA Date",
    key: "eta",
    description: "Estimated arrival date",
    alternateMatches: ["shipping month"],
    fieldType: { type: "input" },
    width: 120,
  },
  {
    label: "Weight",
    key: "weight",
    description: "Product weight (in lbs)",
    alternateMatches: ["weight (lbs.)"],
    fieldType: { type: "input" },
    width: 100,
    validations: [
      { rule: "required", errorMessage: "Required", level: "error" },
      { rule: "regex", value: "^[0-9]*.?[0-9]+$", errorMessage: "Must be a number", level: "error" },
    ],
  },
  {
    label: "Length",
    key: "length",
    description: "Product length (in inches)",
    fieldType: { type: "input" },
    width: 100,
    validations: [
      { rule: "required", errorMessage: "Required", level: "error" },
      { rule: "regex", value: "^[0-9]*.?[0-9]+$", errorMessage: "Must be a number", level: "error" },
    ],
  },
  {
    label: "Width",
    key: "width",
    description: "Product width (in inches)",
    fieldType: { type: "input" },
    width: 100,
    validations: [
      { rule: "required", errorMessage: "Required", level: "error" },
      { rule: "regex", value: "^[0-9]*.?[0-9]+$", errorMessage: "Must be a number", level: "error" },
    ],
  },
  {
    label: "Height",
    key: "height",
    description: "Product height (in inches)",
    fieldType: { type: "input" },
    width: 100,
    validations: [
      { rule: "required", errorMessage: "Required", level: "error" },
      { rule: "regex", value: "^[0-9]*.?[0-9]+$", errorMessage: "Must be a number", level: "error" },
    ],
  },
  {
    label: "Shipping Restrictions",
    key: "ship_restrictions",
    description: "Product shipping restrictions",
    fieldType: {
      type: "select",
      options: [], // Will be populated from API
    },
    width: 190,
    validations: [{ rule: "required", errorMessage: "Required", level: "error" }],
  },
  {
    label: "COO",
    key: "coo",
    description: "2-letter country code (ISO)",
    alternateMatches: ["coo", "country of origin"],
    fieldType: { type: "input" },
    width: 70,
    validations: [
      { rule: "regex", value: "^[A-Z]{2}$", errorMessage: "Must be 2 letters", level: "error" },
    ],
  },
  {
    label: "HTS Code",
    key: "hts_code",
    description: "Harmonized Tariff Schedule code",
    alternateMatches: ["taric","hts"],
    fieldType: { type: "input" },
    width: 130,
    validations: [
      { rule: "regex", value: "^[0-9.]+$", errorMessage: "Must be a number", level: "error" },
    ],
  },
  {
    label: "Size Category",
    key: "size_cat",
    description: "Product size category",
    fieldType: {
      type: "select",
      options: [], // Will be populated from API
    },
    width: 180,
  },
  {
    label: "Description",
    key: "description",
    description: "Detailed product description",
    alternateMatches: ["details/description"],
    fieldType: { 
      type: "input",
      multiline: true 
    },
    width: 500,
    validations: [{ rule: "required", errorMessage: "Required", level: "error" }],
  },
  {
    label: "Private Notes",
    key: "priv_notes",
    description: "Internal notes about the product",
    fieldType: { 
      type: "input",
      multiline: true 
    },
    width: 300,
  },
  {
    label: "Categories",
    key: "categories",
    description: "Product categories",
    fieldType: {
      type: "multi-select",
      options: [], // Will be populated from API
    },
    width: 350,
    validations: [{ rule: "required", errorMessage: "Required", level: "error" }],
  },
  {
    label: "Themes",
    key: "themes",
    description: "Product themes/styles",
    fieldType: {
      type: "multi-select",
      options: [], // Will be populated from API
    },
    width: 300,
  },
  {
    label: "Colors",
    key: "colors",
    description: "Product colors",
    fieldType: {
      type: "multi-select",
      options: [], // Will be populated from API
    },
    width: 200,
  },
] as const;


export function Import() {
  const [isOpen, setIsOpen] = useState(false);
  const [importedData, setImportedData] = useState<any[] | null>(null);
  const [selectedCompany, setSelectedCompany] = useState<string | null>(null);
  const [selectedLine, setSelectedLine] = useState<string | null>(null);
  const [startFromScratch, setStartFromScratch] = useState(false);

  // Fetch initial field options from the API
  const { data: fieldOptions, isLoading: isLoadingOptions } = useQuery({
    queryKey: ["import-field-options"],
    queryFn: async () => {
      const response = await fetch(`${config.apiUrl}/import/field-options`);
      if (!response.ok) {
        throw new Error("Failed to fetch field options");
      }
      return response.json();
    },
  });

  // Fetch product lines when company is selected
  const { data: productLines } = useQuery({
    queryKey: ["product-lines", selectedCompany],
    queryFn: async () => {
      if (!selectedCompany) return [];
      const response = await fetch(`${config.apiUrl}/import/product-lines/${selectedCompany}`);
      if (!response.ok) {
        throw new Error("Failed to fetch product lines");
      }
      return response.json();
    },
    enabled: !!selectedCompany,
  });

  // Fetch sublines when line is selected
  const { data: sublines } = useQuery({
    queryKey: ["sublines", selectedLine],
    queryFn: async () => {
      if (!selectedLine) return [];
      const response = await fetch(`${config.apiUrl}/import/sublines/${selectedLine}`);
      if (!response.ok) {
        throw new Error("Failed to fetch sublines");
      }
      return response.json();
    },
    enabled: !!selectedLine,
  });

  // Handle field value changes
  const handleFieldChange = (field: string, value: any) => {
    console.log('Field change:', field, value);
    if (field === "company") {
      setSelectedCompany(value);
      setSelectedLine(null); // Reset line when company changes
    } else if (field === "line") {
      setSelectedLine(value);
    }
  };

  // Merge base fields with dynamic options
  const importFields = BASE_IMPORT_FIELDS.map(field => {
    if (!fieldOptions) return field;

    switch (field.key) {
      case "company":
        return {
          ...field,
          fieldType: {
            type: "select" as const,
            options: fieldOptions.companies || [],
          },
          onChange: (value: string) => {
            console.log('Company selected:', value);
            handleFieldChange("company", value);
          },
        };
      case "line":
        return {
          ...field,
          fieldType: {
            type: "select" as const,
            options: productLines || [],
          },
          onChange: (value: string) => {
            console.log('Line selected:', value);
            handleFieldChange("line", value);
          },
          disabled: !selectedCompany,
        };
      case "subline":
        return {
          ...field,
          fieldType: {
            type: "select" as const,
            options: sublines || [],
          },
          disabled: !selectedLine,
        };
      case "colors":
        return {
          ...field,
          fieldType: {
            type: "multi-select" as const,
            options: fieldOptions.colors || [],
          },
        };
      case "tax_cat":
        return {
          ...field,
          fieldType: {
            type: "multi-select" as const,
            options: fieldOptions.taxCategories || [],
          },
        };
      case "ship_restrictions":
        return {
          ...field,
          fieldType: {
            type: "select" as const,
            options: fieldOptions.shippingRestrictions || [],
          },
        };
      case "supplier":
        return {
          ...field,
          fieldType: {
            type: "select" as const,
            options: fieldOptions.suppliers || [],
          },
        };
      case "artist":
        return {
          ...field,
          fieldType: {
            type: "select" as const,
            options: fieldOptions.artists || [],
          },
        };
      case "categories":
        return {
          ...field,
          fieldType: {
            type: "multi-select" as const,
            options: fieldOptions.categories || [],
          },
        };
      case "themes":
        return {
          ...field,
          fieldType: {
            type: "multi-select" as const,
            options: fieldOptions.themes || [],
          },
        };
      case "size_cat":
        return {
          ...field,
          fieldType: {
            type: "select" as const,
            options: fieldOptions.sizes || [],
          },
        };
      default:
        return field;
    }
  });

  const handleData = async (data: any, file: File) => {
    try {
      console.log("Imported Data:", data);
      console.log("File:", file);
      setImportedData(data);
      setIsOpen(false);
      toast.success("Data imported successfully");
    } catch (error) {
      toast.error("Failed to import data");
      console.error("Import error:", error);
    }
  };

  if (isLoadingOptions) {
    return (
      <div className="container mx-auto py-6">
        <div className="flex items-center space-x-2">
          <Loader2 className="h-6 w-6 animate-spin text-primary" />
          <h1 className="text-3xl font-bold tracking-tight">Preparing import options...</h1>
        </div>
      </div>
    );
  }

  return (
    <motion.div 
      layout
      transition={{ 
        layout: { 
          duration: 0.15,
          ease: [0.4, 0, 0.2, 1]
        }
      }}
      className="container mx-auto py-6 space-y-4"
    >
      <motion.div 
        layout="position"
        transition={{ duration: 0.15 }}
        className="flex items-center justify-between"
      >
        <h1 className="text-3xl font-bold tracking-tight">Add New Products</h1>
      </motion.div>

      <Card className="max-w-[400px]">
        <CardHeader>
          <CardTitle>Import Data</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <Button onClick={() => setIsOpen(true)} className="w-full">
            Begin Import
          </Button>
        </CardContent>
      </Card>

      {importedData && (
        <Card>
          <CardHeader>
            <CardTitle>Preview Imported Data</CardTitle>
          </CardHeader>
          <CardContent>
            <Code className="p-4 w-full rounded-md border whitespace-pre-wrap">
              {JSON.stringify(importedData, null, 2)}
            </Code>
          </CardContent>
        </Card>
      )}

      <ReactSpreadsheetImport
        isOpen={isOpen}
        onClose={() => {
          setIsOpen(false);
          setStartFromScratch(false);
        }}
        onSubmit={handleData}
        fields={importFields}
        isNavigationEnabled={true}
        initialStepState={startFromScratch ? { type: StepType.validateData, data: [{}] } : undefined}
      />
    </motion.div>
  );
} 