"use client";

import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Plus, Edit, Trash2, X, Upload } from "lucide-react";
import { toast } from "sonner";

interface Category {
  _id: string;
  name: string;
  slug: string;
}

interface Color {
  _id: string;
  name: string;
  hexCode: string;
}

interface Size {
  _id: string;
  name: string;
}

interface ProductVariant {
  size: string;
  color: string;
  sku: string;
  price: number;
  comparePrice?: number;
  inventory: number;
  images: {
    url: string;
    altText?: string;
    sortOrder: number;
  }[];
}

interface Product {
  _id: string;
  name: string;
  slug: string;
  description: string;
  shortDescription?: string;
  category: Category;
  subcategory?: Category;
  sizes: Size[];
  variants: (ProductVariant & {
    size: Size;
    color: Color;
  })[];
  isActive: boolean;
  isFeatured: boolean;
  createdAt: string;
}

export default function ProductsManagement() {
  const [products, setProducts] = useState<Product[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [colors, setColors] = useState<Color[]>([]);
  const [sizes, setSizes] = useState<Size[]>([]);
  const [loading, setLoading] = useState(true);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);
  
  // Product form state
  const [productForm, setProductForm] = useState({
    name: "",
    description: "",
    shortDescription: "",
    category: "",
    subcategory: "",
    sizes: [] as string[],
    variants: [] as ProductVariant[],
    isActive: true,
    isFeatured: false,
    seoTitle: "",
    seoDescription: "",
  });

  // Fetch data
  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      setLoading(true);
      
      const [productsRes, categoriesRes, colorsRes, sizesRes] = await Promise.all([
        fetch('/api/products'),
        fetch('/api/categories'),
        fetch('/api/colors'),
        fetch('/api/sizes')
      ]);

      const [productsData, categoriesData, colorsData, sizesData] = await Promise.all([
        productsRes.json(),
        categoriesRes.json(),
        colorsRes.json(),
        sizesRes.json()
      ]);

      if (productsData.success) setProducts(productsData.data);
      if (categoriesData.success) setCategories(categoriesData.data);
      if (colorsData.success) setColors(colorsData.data);
      if (sizesData.success) setSizes(sizesData.data);
    } catch (error) {
      console.error('Error fetching data:', error);
      toast.error('Failed to load data');
    } finally {
      setLoading(false);
    }
  };

  const resetForm = () => {
    setProductForm({
      name: "",
      description: "",
      shortDescription: "",
      category: "",
      subcategory: "",
      sizes: [],
      variants: [],
      isActive: true,
      isFeatured: false,
      seoTitle: "",
      seoDescription: "",
    });
    setEditingProduct(null);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    try {
      const url = editingProduct ? `/api/products/${editingProduct._id}` : '/api/products';
      const method = editingProduct ? 'PUT' : 'POST';

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(productForm),
      });

      const data = await response.json();

      if (data.success) {
        toast.success(editingProduct ? 'Product updated successfully' : 'Product created successfully');
        setIsDialogOpen(false);
        resetForm();
        fetchData();
      } else {
        toast.error(data.error || 'Failed to save product');
      }
    } catch (error) {
      console.error('Error saving product:', error);
      toast.error('Failed to save product');
    }
  };

  const handleEdit = (product: Product) => {
    setEditingProduct(product);
    setProductForm({
      name: product.name,
      description: product.description,
      shortDescription: product.shortDescription || "",
      category: product.category._id,
      subcategory: product.subcategory?._id || "",
      sizes: product.sizes.map(s => s._id),
      variants: product.variants.map(v => ({
        size: v.size._id,
        color: v.color._id,
        sku: v.sku,
        price: v.price,
        comparePrice: v.comparePrice,
        inventory: v.inventory,
        images: v.images
      })),
      isActive: product.isActive,
      isFeatured: product.isFeatured,
      seoTitle: "",
      seoDescription: "",
    });
    setIsDialogOpen(true);
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this product?')) return;

    try {
      const response = await fetch(`/api/products/${id}`, {
        method: 'DELETE',
      });

      const data = await response.json();

      if (data.success) {
        toast.success('Product deleted successfully');
        fetchData();
      } else {
        toast.error(data.error || 'Failed to delete product');
      }
    } catch (error) {
      console.error('Error deleting product:', error);
      toast.error('Failed to delete product');
    }
  };

  const addVariant = () => {
    setProductForm(prev => ({
      ...prev,
      variants: [...prev.variants, {
        size: "",
        color: "",
        sku: "",
        price: 0,
        comparePrice: 0,
        inventory: 0,
        images: []
      }]
    }));
  };

  const updateVariant = (index: number, field: string, value: any) => {
    setProductForm(prev => ({
      ...prev,
      variants: prev.variants.map((variant, i) => 
        i === index ? { ...variant, [field]: value } : variant
      )
    }));
  };

  const removeVariant = (index: number) => {
    setProductForm(prev => ({
      ...prev,
      variants: prev.variants.filter((_, i) => i !== index)
    }));
  };

  const addImageToVariant = (variantIndex: number) => {
    setProductForm(prev => ({
      ...prev,
      variants: prev.variants.map((variant, i) => 
        i === variantIndex 
          ? { ...variant, images: [...variant.images, { url: "", altText: "", sortOrder: variant.images.length }] }
          : variant
      )
    }));
  };

  const updateVariantImage = (variantIndex: number, imageIndex: number, field: string, value: any) => {
    setProductForm(prev => ({
      ...prev,
      variants: prev.variants.map((variant, i) => 
        i === variantIndex 
          ? {
              ...variant,
              images: variant.images.map((img, j) => 
                j === imageIndex ? { ...img, [field]: value } : img
              )
            }
          : variant
      )
    }));
  };

  const removeVariantImage = (variantIndex: number, imageIndex: number) => {
    setProductForm(prev => ({
      ...prev,
      variants: prev.variants.map((variant, i) => 
        i === variantIndex 
          ? { ...variant, images: variant.images.filter((_, j) => j !== imageIndex) }
          : variant
      )
    }));
  };

  if (loading) {
    return <div className="flex justify-center items-center h-64">Loading...</div>;
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h2 className="text-2xl font-bold">Products Management</h2>
        <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
          <DialogTrigger asChild>
            <Button onClick={() => { resetForm(); setIsDialogOpen(true); }}>
              <Plus className="w-4 h-4 mr-2" />
              Add Product
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>{editingProduct ? 'Edit Product' : 'Add New Product'}</DialogTitle>
            </DialogHeader>
            <form onSubmit={handleSubmit} className="space-y-6">
              {/* Basic Information */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="name">Product Name *</Label>
                  <Input
                    id="name"
                    value={productForm.name}
                    onChange={(e) => setProductForm(prev => ({ ...prev, name: e.target.value }))}
                    required
                  />
                </div>
                <div>
                  <Label htmlFor="category">Category *</Label>
                  <Select value={productForm.category} onValueChange={(value) => setProductForm(prev => ({ ...prev, category: value }))}>
                    <SelectTrigger>
                      <SelectValue placeholder="Select category" />
                    </SelectTrigger>
                    <SelectContent>
                      {categories.map((category) => (
                        <SelectItem key={category._id} value={category._id}>
                          {category.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div>
                <Label htmlFor="description">Description *</Label>
                <Textarea
                  id="description"
                  value={productForm.description}
                  onChange={(e) => setProductForm(prev => ({ ...prev, description: e.target.value }))}
                  required
                />
              </div>

              <div>
                <Label htmlFor="shortDescription">Short Description</Label>
                <Textarea
                  id="shortDescription"
                  value={productForm.shortDescription}
                  onChange={(e) => setProductForm(prev => ({ ...prev, shortDescription: e.target.value }))}
                />
              </div>

              {/* Sizes */}
              <div>
                <Label>Sizes *</Label>
                <div className="flex flex-wrap gap-2 mt-2">
                  {sizes.map((size) => (
                    <label key={size._id} className="flex items-center space-x-2">
                      <input
                        type="checkbox"
                        checked={productForm.sizes.includes(size._id)}
                        onChange={(e) => {
                          if (e.target.checked) {
                            setProductForm(prev => ({ ...prev, sizes: [...prev.sizes, size._id] }));
                          } else {
                            setProductForm(prev => ({ ...prev, sizes: prev.sizes.filter(id => id !== size._id) }));
                          }
                        }}
                        className="rounded"
                      />
                      <span>{size.name}</span>
                    </label>
                  ))}
                </div>
              </div>

              {/* Variants */}
              <div>
                <div className="flex justify-between items-center mb-4">
                  <Label>Variants *</Label>
                  <Button type="button" onClick={addVariant} size="sm">
                    <Plus className="w-4 h-4 mr-2" />
                    Add Variant
                  </Button>
                </div>
                
                {productForm.variants.map((variant, variantIndex) => (
                  <div key={variantIndex} className="border rounded-lg p-4 mb-4 space-y-4">
                    <div className="flex justify-between items-center">
                      <h4 className="font-medium">Variant {variantIndex + 1}</h4>
                      <Button type="button" onClick={() => removeVariant(variantIndex)} variant="destructive" size="sm">
                        <X className="w-4 h-4" />
                      </Button>
                    </div>

                    <div className="grid grid-cols-3 gap-4">
                      <div>
                        <Label>Size *</Label>
                        <Select value={variant.size} onValueChange={(value) => updateVariant(variantIndex, 'size', value)}>
                          <SelectTrigger>
                            <SelectValue placeholder="Select size" />
                          </SelectTrigger>
                          <SelectContent>
                            {sizes.map((size) => (
                              <SelectItem key={size._id} value={size._id}>
                                {size.name}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                      <div>
                        <Label>Color *</Label>
                        <Select value={variant.color} onValueChange={(value) => updateVariant(variantIndex, 'color', value)}>
                          <SelectTrigger>
                            <SelectValue placeholder="Select color" />
                          </SelectTrigger>
                          <SelectContent>
                            {colors.map((color) => (
                              <SelectItem key={color._id} value={color._id}>
                                <div className="flex items-center space-x-2">
                                  <div 
                                    className="w-4 h-4 rounded border"
                                    style={{ backgroundColor: color.hexCode }}
                                  />
                                  <span>{color.name}</span>
                                </div>
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                      <div>
                        <Label htmlFor={`sku-${variantIndex}`}>SKU *</Label>
                        <Input
                          id={`sku-${variantIndex}`}
                          value={variant.sku}
                          onChange={(e) => updateVariant(variantIndex, 'sku', e.target.value)}
                          required
                        />
                      </div>
                    </div>

                    <div className="grid grid-cols-3 gap-4">
                      <div>
                        <Label htmlFor={`price-${variantIndex}`}>Price *</Label>
                        <Input
                          id={`price-${variantIndex}`}
                          type="number"
                          step="0.01"
                          value={variant.price}
                          onChange={(e) => updateVariant(variantIndex, 'price', parseFloat(e.target.value) || 0)}
                          required
                        />
                      </div>
                      <div>
                        <Label htmlFor={`comparePrice-${variantIndex}`}>Compare Price</Label>
                        <Input
                          id={`comparePrice-${variantIndex}`}
                          type="number"
                          step="0.01"
                          value={variant.comparePrice || ''}
                          onChange={(e) => updateVariant(variantIndex, 'comparePrice', parseFloat(e.target.value) || 0)}
                        />
                      </div>
                      <div>
                        <Label htmlFor={`inventory-${variantIndex}`}>Inventory *</Label>
                        <Input
                          id={`inventory-${variantIndex}`}
                          type="number"
                          value={variant.inventory}
                          onChange={(e) => updateVariant(variantIndex, 'inventory', parseInt(e.target.value) || 0)}
                          required
                        />
                      </div>
                    </div>

                    {/* Images */}
                    <div>
                      <div className="flex justify-between items-center mb-2">
                        <Label>Images *</Label>
                        <Button type="button" onClick={() => addImageToVariant(variantIndex)} size="sm">
                          <Upload className="w-4 h-4 mr-2" />
                          Add Image
                        </Button>
                      </div>
                      
                      {variant.images.map((image, imageIndex) => (
                        <div key={imageIndex} className="flex items-center space-x-2 mb-2">
                          <Input
                            placeholder="Image URL"
                            value={image.url}
                            onChange={(e) => updateVariantImage(variantIndex, imageIndex, 'url', e.target.value)}
                            required
                          />
                          <Input
                            placeholder="Alt text"
                            value={image.altText || ''}
                            onChange={(e) => updateVariantImage(variantIndex, imageIndex, 'altText', e.target.value)}
                          />
                          <Button type="button" onClick={() => removeVariantImage(variantIndex, imageIndex)} variant="destructive" size="sm">
                            <X className="w-4 h-4" />
                          </Button>
                        </div>
                      ))}
                    </div>
                  </div>
                ))}
              </div>

              {/* Settings */}
              <div className="flex items-center space-x-4">
                <div className="flex items-center space-x-2">
                  <Switch
                    id="isActive"
                    checked={productForm.isActive}
                    onCheckedChange={(checked) => setProductForm(prev => ({ ...prev, isActive: checked }))}
                  />
                  <Label htmlFor="isActive">Active</Label>
                </div>
                <div className="flex items-center space-x-2">
                  <Switch
                    id="isFeatured"
                    checked={productForm.isFeatured}
                    onCheckedChange={(checked) => setProductForm(prev => ({ ...prev, isFeatured: checked }))}
                  />
                  <Label htmlFor="isFeatured">Featured</Label>
                </div>
              </div>

              <div className="flex justify-end space-x-2">
                <Button type="button" variant="outline" onClick={() => setIsDialogOpen(false)}>
                  Cancel
                </Button>
                <Button type="submit">
                  {editingProduct ? 'Update' : 'Create'} Product
                </Button>
              </div>
            </form>
          </DialogContent>
        </Dialog>
      </div>

      {/* Products Table */}
      <div className="border rounded-lg">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Name</TableHead>
              <TableHead>Category</TableHead>
              <TableHead>Sizes</TableHead>
              <TableHead>Variants</TableHead>
              <TableHead>Status</TableHead>
              <TableHead>Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {products.map((product) => (
              <TableRow key={product._id}>
                <TableCell className="font-medium">{product.name}</TableCell>
                <TableCell>{product.category.name}</TableCell>
                <TableCell>
                  <div className="flex flex-wrap gap-1">
                    {product.sizes.map((size) => (
                      <Badge key={size._id} variant="secondary">{size.name}</Badge>
                    ))}
                  </div>
                </TableCell>
                <TableCell>{product.variants.length} variants</TableCell>
                <TableCell>
                  <div className="flex gap-1">
                    {product.isActive && <Badge variant="default">Active</Badge>}
                    {product.isFeatured && <Badge variant="secondary">Featured</Badge>}
                  </div>
                </TableCell>
                <TableCell>
                  <div className="flex space-x-2">
                    <Button size="sm" variant="outline" onClick={() => handleEdit(product)}>
                      <Edit className="w-4 h-4" />
                    </Button>
                    <Button size="sm" variant="destructive" onClick={() => handleDelete(product._id)}>
                      <Trash2 className="w-4 h-4" />
                    </Button>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}
