import React from 'react';
import { __ } from '@/lib/i18n';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Plus, X, Layers } from 'lucide-react';
import { toast } from 'sonner';

export type ProductVariant = {
  id?: number;
  attributes: Record<string, string>;
  sku?: string;
  regular_price?: string;
  sale_price?: string;
  stock_quantity?: number;
  manage_stock?: boolean;
  stock_status?: 'instock' | 'outofstock' | 'onbackorder';
};

type VariationsTabProps = {
  attributes: Array<{ name: string; options: string[]; variation: boolean }>;
  setAttributes: (value: Array<{ name: string; options: string[]; variation: boolean }>) => void;
  variations: ProductVariant[];
  setVariations: (value: ProductVariant[]) => void;
  regularPrice: string;
};

export function VariationsTab({
  attributes,
  setAttributes,
  variations,
  setVariations,
  regularPrice,
}: VariationsTabProps) {
  const addAttribute = () => {
    setAttributes([...attributes, { name: '', options: [], variation: false }]);
  };

  const removeAttribute = (index: number) => {
    setAttributes(attributes.filter((_, i) => i !== index));
  };

  const updateAttribute = (index: number, field: string, value: any) => {
    const updated = [...attributes];
    updated[index] = { ...updated[index], [field]: value };
    setAttributes(updated);
  };

  const generateVariations = () => {
    const variationAttrs = attributes.filter(attr => attr.variation && attr.options.length > 0);
    
    if (variationAttrs.length === 0) {
      toast.warning(__('Please add at least one variation attribute with options'));
      return;
    }

    // Generate all combinations
    const combinations: Record<string, string>[] = [];
    const generate = (index: number, current: Record<string, string>) => {
      if (index === variationAttrs.length) {
        combinations.push({ ...current });
        return;
      }
      const attr = variationAttrs[index];
      for (const option of attr.options) {
        generate(index + 1, { ...current, [attr.name]: option });
      }
    };
    generate(0, {});

    const newVariations: ProductVariant[] = combinations.map(attrs => ({
      attributes: attrs,
      sku: '',
      regular_price: regularPrice || '', // Pre-fill with base price
      sale_price: '',
      stock_quantity: 0,
      manage_stock: false,
      stock_status: 'instock',
    }));

    setVariations(newVariations);
    toast.success(__(`Generated ${newVariations.length} variations`));
  };

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle>{__('Product Variations')}</CardTitle>
            <CardDescription>{__('Define attributes and generate variations')}</CardDescription>
          </div>
          <Button type="button" variant="outline" size="sm" onClick={addAttribute}>
            <Plus className="w-4 h-4 mr-2" />
            {__('Add Attribute')}
          </Button>
        </div>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* Attributes */}
        {attributes.length === 0 ? (
          <div className="text-center py-8 text-muted-foreground">
            <Layers className="w-12 h-12 mx-auto mb-3 opacity-50" />
            <p>{__('No attributes yet. Add attributes like Size, Color, etc.')}</p>
          </div>
        ) : (
          attributes.map((attr, index) => (
            <Card key={index} className="border-2">
              <CardContent className="pt-6 space-y-3">
                <div className="flex items-center justify-between">
                  <Badge variant="outline">{__('Attribute')} {index + 1}</Badge>
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => removeAttribute(index)}
                  >
                    <X className="w-4 h-4" />
                  </Button>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  <div>
                    <Label>{__('Attribute Name')}</Label>
                    <Input
                      value={attr.name}
                      onChange={(e) => updateAttribute(index, 'name', e.target.value)}
                      placeholder={__('e.g., Color, Size, Material')}
                      className="mt-1.5"
                    />
                  </div>
                  <div>
                    <Label>{__('Options')}</Label>
                    <Input
                      key={`options-${index}-${attr.options.length}`}
                      defaultValue={attr.options.join(', ')}
                      onBlur={(e) => {
                        const input = e.target.value;
                        // Split by comma or pipe, trim whitespace
                        const options = input
                          .split(/[,|]/)
                          .map(s => s.trim())
                          .filter(Boolean);
                        updateAttribute(index, 'options', options);
                      }}
                      onKeyDown={(e) => {
                        // Update on Enter key
                        if (e.key === 'Enter') {
                          e.currentTarget.blur();
                        }
                      }}
                      placeholder={__('Red, Blue, Green (comma or pipe separated)')}
                      className="mt-1.5"
                    />
                    <p className="text-xs text-muted-foreground mt-1">
                      {__('Type naturally: Red, Blue, Green (press Enter or click away)')}
                    </p>
                  </div>
                </div>

                <div className="flex items-center space-x-2">
                  <Checkbox
                    id={`variation-${index}`}
                    checked={attr.variation}
                    onCheckedChange={(checked) => updateAttribute(index, 'variation', checked)}
                  />
                  <Label htmlFor={`variation-${index}`} className="cursor-pointer font-normal">
                    {__('Use for variations')}
                  </Label>
                </div>
              </CardContent>
            </Card>
          ))
        )}

        {/* Generate Variations Button */}
        {attributes.some(attr => attr.variation && attr.options.length > 0) && (
          <>
            <Separator />
            <Button type="button" onClick={generateVariations} className="w-full">
              <Layers className="w-4 h-4 mr-2" />
              {__('Generate Variations')}
            </Button>
          </>
        )}

        {/* Variations List */}
        {variations.length > 0 && (
          <>
            <Separator />
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <h4 className="font-medium">{__('Generated Variations')}</h4>
                <Badge>{variations.length}</Badge>
              </div>
              {variations.map((variation, index) => (
                <Card key={index}>
                  <CardContent className="pt-6 space-y-3">
                    <div className="font-medium text-sm flex flex-wrap gap-2">
                      {Object.entries(variation.attributes).map(([key, value]) => (
                        <Badge key={key} variant="secondary">
                          {key}: {value}
                        </Badge>
                      ))}
                    </div>
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                      <Input
                        placeholder={__('SKU')}
                        value={variation.sku || ''}
                        onChange={(e) => {
                          const updated = [...variations];
                          updated[index].sku = e.target.value;
                          setVariations(updated);
                        }}
                      />
                      <Input
                        type="number"
                        step="0.01"
                        placeholder={__('Price')}
                        value={variation.regular_price || ''}
                        onChange={(e) => {
                          const updated = [...variations];
                          updated[index].regular_price = e.target.value;
                          setVariations(updated);
                        }}
                      />
                      <Input
                        type="number"
                        step="0.01"
                        placeholder={__('Sale')}
                        value={variation.sale_price || ''}
                        onChange={(e) => {
                          const updated = [...variations];
                          updated[index].sale_price = e.target.value;
                          setVariations(updated);
                        }}
                      />
                      <Input
                        type="number"
                        placeholder={__('Stock')}
                        value={variation.stock_quantity || ''}
                        onChange={(e) => {
                          const updated = [...variations];
                          updated[index].stock_quantity = parseInt(e.target.value) || 0;
                          setVariations(updated);
                        }}
                      />
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          </>
        )}
      </CardContent>
    </Card>
  );
}
