import React, { useState } 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 { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Plus, X, Layers, Image as ImageIcon, Copy, Check, ExternalLink } from 'lucide-react';
import { toast } from 'sonner';
import { getStoreCurrency } from '@/lib/currency';
import { openWPMediaImage } from '@/lib/wp-media';

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

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;
  productId?: number;
};

export function VariationsTab({
  attributes,
  setAttributes,
  variations,
  setVariations,
  regularPrice,
  productId,
}: VariationsTabProps) {
  const store = getStoreCurrency();
  const [copiedLink, setCopiedLink] = useState<string | null>(null);

  const siteUrl = window.location.origin;
  const spaPagePath = (window as any).WNW_CONFIG?.storeUrl ? new URL((window as any).WNW_CONFIG.storeUrl).pathname : '/store';

  const generateLink = (variationId: number, redirect: 'cart' | 'checkout' = 'cart') => {
    if (!productId) return '';
    const params = new URLSearchParams();
    params.set('add-to-cart', productId.toString());
    params.set('variation_id', variationId.toString());
    params.set('redirect', redirect);
    return `${siteUrl}${spaPagePath}?${params.toString()}`;
  };

  const copyToClipboard = async (link: string, label: string) => {
    try {
      await navigator.clipboard.writeText(link);
      setCopiedLink(link);
      toast.success(`${label} link copied!`);
      setTimeout(() => setCopiedLink(null), 2000);
    } catch (err) {
      toast.error('Failed to copy link');
    }
  };

  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,
      virtual: false,
      downloadable: 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>
                    {/* Variation Image */}
                    <div className="mb-3">
                      <Label className="text-xs">{__('Variation Image (Optional)')}</Label>
                      <div className="flex gap-2 mt-1.5">
                        {variation.image ? (
                          <div className="relative w-16 h-16 border rounded overflow-hidden group">
                            <img src={variation.image} alt="Variation" className="w-full h-full object-cover" />
                            <button
                              type="button"
                              onClick={() => {
                                const updated = [...variations];
                                updated[index].image = undefined;
                                setVariations(updated);
                              }}
                              className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center"
                            >
                              <X className="h-4 w-4 text-white" />
                            </button>
                          </div>
                        ) : (
                          <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={() => {
                              openWPMediaImage((file) => {
                                const updated = [...variations];
                                updated[index].image = file.url;
                                setVariations(updated);
                              });
                            }}
                          >
                            <ImageIcon className="mr-2 h-3 w-3" />
                            {__('Add Image')}
                          </Button>
                        )}
                      </div>
                    </div>

                    {/* License Duration - only show if licensing is enabled on product */}
                    <div className="col-span-2 md:col-span-4">
                      <Label className="text-xs">{__('License Duration (Days)')}</Label>
                      <Input
                        type="number"
                        min="0"
                        placeholder={__('Leave empty to use product default')}
                        value={variation.license_duration_days || ''}
                        onChange={(e) => {
                          const updated = [...variations];
                          updated[index].license_duration_days = e.target.value;
                          setVariations(updated);
                        }}
                        className="mt-1"
                      />
                      <p className="text-xs text-muted-foreground mt-1">
                        {__('Override license duration for this variation. 0 = never expires.')}
                      </p>
                    </div>

                    {/* Variation Options */}

                    <div className="flex flex-wrap gap-4 pt-2">
                      <div className="flex items-center space-x-2">
                        <Checkbox
                          id={`virtual-${index}`}
                          checked={variation.virtual || false}
                          onCheckedChange={(checked) => {
                            const updated = [...variations];
                            updated[index].virtual = checked as boolean;
                            setVariations(updated);
                          }}
                        />
                        <Label htmlFor={`virtual-${index}`} className="cursor-pointer font-normal text-xs">
                          {__('Virtual')}
                        </Label>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Checkbox
                          id={`downloadable-${index}`}
                          checked={variation.downloadable || false}
                          onCheckedChange={(checked) => {
                            const updated = [...variations];
                            updated[index].downloadable = checked as boolean;
                            setVariations(updated);
                          }}
                        />
                        <Label htmlFor={`downloadable-${index}`} className="cursor-pointer font-normal text-xs">
                          {__('Downloadable')}
                        </Label>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Checkbox
                          id={`manage-stock-${index}`}
                          checked={variation.manage_stock || false}
                          onCheckedChange={(checked) => {
                            const updated = [...variations];
                            updated[index].manage_stock = checked as boolean;
                            setVariations(updated);
                          }}
                        />
                        <Label htmlFor={`manage-stock-${index}`} className="cursor-pointer font-normal text-xs">
                          {__('Manage Stock')}
                        </Label>
                      </div>
                    </div>

                    <div className="grid grid-cols-2 md:grid-cols-4 gap-3 pt-2">
                      <Input
                        placeholder={__('SKU')}
                        value={variation.sku || ''}
                        onChange={(e) => {
                          const updated = [...variations];
                          updated[index].sku = e.target.value;
                          setVariations(updated);
                        }}
                      />
                      <div className="relative">
                        <span className="absolute left-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground font-medium">
                          {store.symbol}
                        </span>
                        <Input
                          type="number"
                          step={store.decimals === 0 ? '1' : '0.01'}
                          placeholder={__('Price')}
                          value={variation.regular_price || ''}
                          onChange={(e) => {
                            const updated = [...variations];
                            updated[index].regular_price = e.target.value;
                            setVariations(updated);
                          }}
                          className="pl-8 pr-3 text-right"
                        />
                      </div>
                      <div className="relative">
                        <span className="absolute left-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground font-medium">
                          {store.symbol}
                        </span>
                        <Input
                          type="number"
                          step={store.decimals === 0 ? '1' : '0.01'}
                          placeholder={__('Sale')}
                          value={variation.sale_price || ''}
                          onChange={(e) => {
                            const updated = [...variations];
                            updated[index].sale_price = e.target.value;
                            setVariations(updated);
                          }}
                          className="pl-8 pr-3 text-right"
                        />
                      </div>
                      <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>

                    {/* Direct Cart Links */}
                    {productId && variation.id && (
                      <div className="mt-4 pt-4 border-t space-y-2">
                        <Label className="text-xs font-medium text-muted-foreground">
                          {__('Direct-to-Cart Links')}
                        </Label>
                        <div className="flex gap-2">
                          <Button
                            type="button"
                            size="sm"
                            variant="outline"
                            onClick={() => copyToClipboard(generateLink(variation.id!, 'cart'), 'Cart')}
                            className="flex-1"
                          >
                            {copiedLink === generateLink(variation.id!, 'cart') ? (
                              <Check className="h-3 w-3 mr-1" />
                            ) : (
                              <Copy className="h-3 w-3 mr-1" />
                            )}
                            {__('Copy Cart Link')}
                          </Button>
                          <Button
                            type="button"
                            size="sm"
                            variant="outline"
                            onClick={() => copyToClipboard(generateLink(variation.id!, 'checkout'), 'Checkout')}
                            className="flex-1"
                          >
                            {copiedLink === generateLink(variation.id!, 'checkout') ? (
                              <Check className="h-3 w-3 mr-1" />
                            ) : (
                              <Copy className="h-3 w-3 mr-1" />
                            )}
                            {__('Copy Checkout Link')}
                          </Button>
                        </div>
                      </div>
                    )}
                  </CardContent>
                </Card>
              ))}
            </div>
          </>
        )}
      </CardContent>
    </Card>
  );
}
