import React, { useState } from 'react';
import { __ } from '@/lib/i18n';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Checkbox } from '@/components/ui/checkbox';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import { DollarSign, Upload, X, Image as ImageIcon, Copy, Check, Key, Repeat, Percent } from 'lucide-react';
import { toast } from 'sonner';
import { getStoreCurrency } from '@/lib/currency';
import { RichTextEditor } from '@/components/RichTextEditor';
import { openWPMediaGallery } from '@/lib/wp-media';
import { useModules } from '@/hooks/useModules';

type GeneralTabProps = {
  name: string;
  setName: (value: string) => void;
  type: 'simple' | 'variable' | 'grouped' | 'external';
  setType: (value: 'simple' | 'variable' | 'grouped' | 'external') => void;
  status: 'publish' | 'draft' | 'pending' | 'private';
  setStatus: (value: 'publish' | 'draft' | 'pending' | 'private') => void;
  description: string;
  setDescription: (value: string) => void;
  shortDescription: string;
  setShortDescription: (value: string) => void;
  virtual: boolean;
  setVirtual: (value: boolean) => void;
  downloadable: boolean;
  setDownloadable: (value: boolean) => void;
  featured: boolean;
  setFeatured: (value: boolean) => void;
  // Images
  images: string[];
  setImages: (value: string[]) => void;
  // Pricing props
  sku: string;
  setSku: (value: string) => void;
  regularPrice: string;
  setRegularPrice: (value: string) => void;
  salePrice: string;
  setSalePrice: (value: string) => void;
  // For copy links
  productId?: number;
  // Licensing
  licensingEnabled?: boolean;
  setLicensingEnabled?: (value: boolean) => void;
  licenseActivationLimit?: string;
  setLicenseActivationLimit?: (value: string) => void;
  licenseDurationDays?: string;
  setLicenseDurationDays?: (value: string) => void;
  licenseActivationMethod?: '' | 'api' | 'oauth';
  setLicenseActivationMethod?: (value: '' | 'api' | 'oauth') => void;
  // Subscription
  subscriptionEnabled?: boolean;
  setSubscriptionEnabled?: (value: boolean) => void;
  subscriptionPeriod?: 'day' | 'week' | 'month' | 'year';
  setSubscriptionPeriod?: (value: 'day' | 'week' | 'month' | 'year') => void;
  subscriptionInterval?: string;
  setSubscriptionInterval?: (value: string) => void;
  subscriptionTrialDays?: string;
  setSubscriptionTrialDays?: (value: string) => void;
  subscriptionSignupFee?: string;
  setSubscriptionSignupFee?: (value: string) => void;
  // Affiliate
  affiliateEnabled?: boolean;
  setAffiliateEnabled?: (value: boolean) => void;
  affiliateCommissionRate?: string;
  setAffiliateCommissionRate?: (value: string) => void;
};

export function GeneralTab({
  name,
  setName,
  type,
  setType,
  status,
  setStatus,
  description,
  setDescription,
  shortDescription,
  setShortDescription,
  virtual,
  setVirtual,
  downloadable,
  setDownloadable,
  featured,
  setFeatured,
  images,
  setImages,
  sku,
  setSku,
  regularPrice,
  setRegularPrice,
  salePrice,
  setSalePrice,
  productId,
  licensingEnabled,
  setLicensingEnabled,
  licenseActivationLimit,
  setLicenseActivationLimit,
  licenseDurationDays,
  setLicenseDurationDays,
  licenseActivationMethod,
  setLicenseActivationMethod,
  subscriptionEnabled,
  setSubscriptionEnabled,
  subscriptionPeriod,
  setSubscriptionPeriod,
  subscriptionInterval,
  setSubscriptionInterval,
  subscriptionTrialDays,
  setSubscriptionTrialDays,
  subscriptionSignupFee,
  setSubscriptionSignupFee,
  affiliateEnabled,
  setAffiliateEnabled,
  affiliateCommissionRate,
  setAffiliateCommissionRate,
}: GeneralTabProps) {
  const savingsPercent =
    salePrice && regularPrice && parseFloat(salePrice) < parseFloat(regularPrice)
      ? Math.round((1 - parseFloat(salePrice) / parseFloat(regularPrice)) * 100)
      : 0;

  const store = getStoreCurrency();
  const { isEnabled } = useModules();

  // Copy link state and helpers
  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 generateSimpleLink = (redirect: 'cart' | 'checkout' = 'cart') => {
    if (!productId) return '';
    const params = new URLSearchParams();
    params.set('add-to-cart', productId.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');
    }
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>{__('Basic Information')}</CardTitle>
        <CardDescription>{__('Essential product details')}</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* Product Name */}
        <div>
          <Label htmlFor="name">{__('Product Name')} *</Label>
          <Input
            id="name"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder={__('e.g., Premium Cotton T-Shirt')}
            required
            className="mt-1.5"
          />
          <p className="text-xs text-muted-foreground mt-1">
            {__('Give your product a short and clear name')}
          </p>
        </div>

        {/* Type & Status */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <Label htmlFor="type">{__('Product Type')}</Label>
            <Select value={type} onValueChange={(v: any) => setType(v)}>
              <SelectTrigger id="type" className="mt-1.5">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectGroup>
                  <SelectItem value="simple">{__('Simple Product')}</SelectItem>
                  <SelectItem value="variable">{__('Variable Product')}</SelectItem>
                  <SelectItem value="grouped">{__('Grouped Product')}</SelectItem>
                  <SelectItem value="external">{__('External Product')}</SelectItem>
                </SelectGroup>
              </SelectContent>
            </Select>
            <p className="text-xs text-muted-foreground mt-1">
              {type === 'simple' && __('A standalone product')}
              {type === 'variable' && __('Product with variations (size, color, etc.)')}
              {type === 'grouped' && __('A collection of related products')}
              {type === 'external' && __('Product sold on another website')}
            </p>
          </div>

          <div>
            <Label htmlFor="status">{__('Status')}</Label>
            <Select value={status} onValueChange={(v: any) => setStatus(v)}>
              <SelectTrigger id="status" className="mt-1.5">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectGroup>
                  <SelectItem value="publish">{__('Published')}</SelectItem>
                  <SelectItem value="draft">{__('Draft')}</SelectItem>
                  <SelectItem value="pending">{__('Pending')}</SelectItem>
                  <SelectItem value="private">{__('Private')}</SelectItem>
                </SelectGroup>
              </SelectContent>
            </Select>
          </div>
        </div>

        <Separator />

        {/* Description */}
        <div>
          <Label htmlFor="description">{__('Description')}</Label>
          <div className="mt-1.5">
            <RichTextEditor
              value={description}
              onChange={setDescription}
              placeholder={__('Describe your product in detail...')}
            />
          </div>
          <p className="text-xs text-muted-foreground mt-1">
            {__('Full product description for the product page')}
          </p>
        </div>

        {/* Short Description */}
        <div>
          <Label htmlFor="short_description">{__('Short Description')}</Label>
          <Textarea
            id="short_description"
            value={shortDescription}
            onChange={(e) => setShortDescription(e.target.value)}
            placeholder={__('Brief summary...')}
            rows={3}
            className="mt-1.5"
          />
          <p className="text-xs text-muted-foreground mt-1">
            {__('Brief summary shown in product listings')}
          </p>
        </div>

        {/* Product Images */}
        <Separator />
        <div>
          <Label>{__('Product Images')}</Label>
          <p className="text-xs text-muted-foreground mt-1 mb-3">
            {__('First image will be the featured image. Drag to reorder.')}
          </p>

          {/* Image Upload Button */}
          <div className="space-y-3">
            <Button
              type="button"
              variant="outline"
              onClick={() => {
                openWPMediaGallery((files) => {
                  const newImages = files.map(file => file.url);
                  setImages([...images, ...newImages]);
                });
              }}
              className="w-full"
            >
              <Upload className="mr-2 h-4 w-4" />
              {__('Add Images from Media Library')}
            </Button>

            {/* Image Preview Grid - Sortable */}
            {images.length > 0 && (
              <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                {images.map((image, index) => (
                  <div
                    key={index}
                    draggable
                    onDragStart={(e) => {
                      e.dataTransfer.effectAllowed = 'move';
                      e.dataTransfer.setData('text/plain', index.toString());
                      e.currentTarget.classList.add('opacity-50');
                    }}
                    onDragEnd={(e) => {
                      e.currentTarget.classList.remove('opacity-50');
                    }}
                    onDragOver={(e) => {
                      e.preventDefault();
                      e.dataTransfer.dropEffect = 'move';
                      e.currentTarget.classList.add('ring-2', 'ring-primary', 'ring-offset-2');
                    }}
                    onDragLeave={(e) => {
                      e.currentTarget.classList.remove('ring-2', 'ring-primary', 'ring-offset-2');
                    }}
                    onDrop={(e) => {
                      e.preventDefault();
                      e.currentTarget.classList.remove('ring-2', 'ring-primary', 'ring-offset-2');
                      const fromIndex = parseInt(e.dataTransfer.getData('text/plain'));
                      const toIndex = index;

                      if (fromIndex !== toIndex) {
                        const newImages = [...images];
                        const [movedImage] = newImages.splice(fromIndex, 1);
                        newImages.splice(toIndex, 0, movedImage);
                        setImages(newImages);
                      }
                    }}
                    className="relative group aspect-square border-2 border-dashed border-gray-300 rounded-lg overflow-hidden bg-gray-50 cursor-move hover:border-primary transition-all"
                  >
                    <img
                      src={image}
                      alt={`Product ${index + 1}`}
                      className="w-full h-full object-cover pointer-events-none"
                    />
                    {index === 0 && (
                      <div className="absolute top-2 left-2 bg-primary text-primary-foreground text-xs px-2 py-1 rounded font-medium">
                        {__('Featured')}
                      </div>
                    )}
                    <button
                      type="button"
                      onClick={() => {
                        const newImages = images.filter((_, i) => i !== index);
                        setImages(newImages);
                      }}
                      className="absolute top-2 right-2 bg-red-600 text-white p-1.5 rounded-full opacity-0 group-hover:opacity-100 transition-opacity hover:bg-red-700"
                    >
                      <X className="h-3 w-3" />
                    </button>
                    <div className="absolute bottom-2 left-2 bg-black/50 text-white text-xs px-2 py-1 rounded opacity-0 group-hover:opacity-100 transition-opacity">
                      {__('Drag to reorder')}
                    </div>
                  </div>
                ))}
              </div>
            )}

            {images.length === 0 && (
              <div className="border-2 border-dashed rounded-lg p-8 text-center text-muted-foreground">
                <ImageIcon className="mx-auto h-12 w-12 mb-2 opacity-50" />
                <p className="text-sm">{__('No images uploaded yet')}</p>
              </div>
            )}
          </div>
        </div>

        {/* Pricing Section */}
        <Separator />
        <div className="space-y-4">
          <h3 className="font-medium">{__('Pricing')}</h3>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <Label htmlFor="sku">{__('SKU')}</Label>
              <Input
                id="sku"
                value={sku}
                onChange={(e) => setSku(e.target.value)}
                placeholder={__('PROD-001')}
                className="mt-1.5 font-mono"
              />
              <p className="text-xs text-muted-foreground mt-1">
                {__('Stock Keeping Unit (optional)')}
              </p>
            </div>

            <div>
              <Label htmlFor="regular_price">
                {__('Regular Price')} {type === 'simple' && '*'}
              </Label>
              <div className="relative mt-1.5">
                <span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm text-muted-foreground font-medium">
                  {store.symbol}
                </span>
                <Input
                  id="regular_price"
                  type="number"
                  step={store.decimals === 0 ? '1' : '0.01'}
                  value={regularPrice}
                  onChange={(e) => setRegularPrice(e.target.value)}
                  placeholder={store.decimals === 0 ? '0' : '0.00'}
                  required={type === 'simple'}
                  className="pl-9 pr-3 text-right"
                />
              </div>
              <p className="text-xs text-muted-foreground mt-1">
                {type === 'variable'
                  ? __('Base price (can override per variation)')
                  : __('Base price before discounts')}
              </p>
            </div>

            <div>
              <Label htmlFor="sale_price">{__('Sale Price')}</Label>
              <div className="relative mt-1.5">
                <span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm text-muted-foreground font-medium">
                  {store.symbol}
                </span>
                <Input
                  id="sale_price"
                  type="number"
                  step={store.decimals === 0 ? '1' : '0.01'}
                  value={salePrice}
                  onChange={(e) => setSalePrice(e.target.value)}
                  placeholder={store.decimals === 0 ? '0' : '0.00'}
                  className="pl-9 pr-3 text-right"
                />
              </div>
              <p className="text-xs text-muted-foreground mt-1">
                {__('Discounted price (optional)')}
              </p>
            </div>
          </div>

          {savingsPercent > 0 && (
            <div className="bg-emerald-50 dark:bg-emerald-900/20 border border-emerald-200 dark:border-emerald-800 rounded-lg p-3">
              <p className="text-sm text-emerald-800 dark:text-emerald-300">
                💰 {__('Customers save')} {savingsPercent}%
              </p>
            </div>
          )}
        </div>

        {/* Additional Options */}
        <Separator />
        <div className="space-y-3">
          <Label>{__('Additional Options')}</Label>
          <div className="flex flex-col gap-3">
            {type === 'simple' && (
              <>
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="virtual"
                    checked={virtual}
                    onCheckedChange={(checked) => setVirtual(checked as boolean)}
                  />
                  <Label htmlFor="virtual" className="cursor-pointer font-normal">
                    {__('Virtual product (no shipping required)')}
                  </Label>
                </div>

                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="downloadable"
                    checked={downloadable}
                    onCheckedChange={(checked) => setDownloadable(checked as boolean)}
                  />
                  <Label htmlFor="downloadable" className="cursor-pointer font-normal">
                    {__('Downloadable product')}
                  </Label>
                </div>
              </>
            )}

            <div className="flex items-center space-x-2">
              <Checkbox
                id="featured"
                checked={featured}
                onCheckedChange={(checked) => setFeatured(checked as boolean)}
              />
              <Label htmlFor="featured" className="cursor-pointer font-normal">
                {__('Featured product (show in featured sections)')}
              </Label>
            </div>

            {/* Licensing option */}
            {isEnabled('licensing') && setLicensingEnabled && (
              <>
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="licensing-enabled"
                    checked={licensingEnabled || false}
                    onCheckedChange={(checked) => setLicensingEnabled(checked as boolean)}
                  />
                  <Label htmlFor="licensing-enabled" className="cursor-pointer font-normal flex items-center gap-1">
                    <Key className="h-3 w-3" />
                    {__('Enable licensing for this product')}
                  </Label>
                </div>

                {/* Licensing settings panel */}
                {licensingEnabled && (
                  <div className="ml-6 p-3 bg-muted/50 rounded-lg space-y-3">
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <Label className="text-xs">{__('Activation Limit')}</Label>
                        <Input
                          type="number"
                          min="0"
                          placeholder={__('0 = unlimited')}
                          value={licenseActivationLimit || ''}
                          onChange={(e) => setLicenseActivationLimit?.(e.target.value)}
                          className="mt-1"
                        />
                        <p className="text-xs text-muted-foreground mt-1">
                          {__('0 or empty = use global default')}
                        </p>
                      </div>
                      <div>
                        <Label className="text-xs">{__('License Duration (Days)')}</Label>
                        <Input
                          type="number"
                          min="0"
                          placeholder={__('365')}
                          value={licenseDurationDays || ''}
                          onChange={(e) => setLicenseDurationDays?.(e.target.value)}
                          className="mt-1"
                        />
                        <p className="text-xs text-muted-foreground mt-1">
                          {__('0 = never expires')}
                        </p>
                      </div>
                    </div>
                    {setLicenseActivationMethod && (
                      <div>
                        <Label className="text-xs">{__('Activation Method')}</Label>
                        <Select
                          value={licenseActivationMethod || 'default'}
                          onValueChange={(v) => setLicenseActivationMethod(v === 'default' ? '' : v as '' | 'api' | 'oauth')}
                        >
                          <SelectTrigger className="mt-1">
                            <SelectValue placeholder={__('Use Site Default')} />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="default">{__('Use Site Default')}</SelectItem>
                            <SelectItem value="api">{__('Simple API (license key only)')}</SelectItem>
                            <SelectItem value="oauth">{__('Secure OAuth (requires login)')}</SelectItem>
                          </SelectContent>
                        </Select>
                        <p className="text-xs text-muted-foreground mt-1">
                          {__('Override site-level activation method for this product')}
                        </p>
                      </div>
                    )}
                  </div>
                )}
              </>
            )}

            {/* Subscription option */}
            {isEnabled('subscription') && setSubscriptionEnabled && (
              <>
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="subscription-enabled"
                    checked={subscriptionEnabled || false}
                    onCheckedChange={(checked) => setSubscriptionEnabled(checked as boolean)}
                  />
                  <Label htmlFor="subscription-enabled" className="cursor-pointer font-normal flex items-center gap-1">
                    <Repeat className="h-3 w-3" />
                    {__('Enable subscription for this product')}
                  </Label>
                </div>

                {/* Subscription settings panel */}
                {subscriptionEnabled && (
                  <div className="ml-6 p-3 bg-muted/50 rounded-lg space-y-3">
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <Label className="text-xs">{__('Billing Period')}</Label>
                        <Select
                          value={subscriptionPeriod || 'month'}
                          onValueChange={(v: any) => setSubscriptionPeriod?.(v)}
                        >
                          <SelectTrigger className="mt-1">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectGroup>
                              <SelectItem value="day">{__('Day')}</SelectItem>
                              <SelectItem value="week">{__('Week')}</SelectItem>
                              <SelectItem value="month">{__('Month')}</SelectItem>
                              <SelectItem value="year">{__('Year')}</SelectItem>
                            </SelectGroup>
                          </SelectContent>
                        </Select>
                      </div>
                      <div>
                        <Label className="text-xs">{__('Billing Interval')}</Label>
                        <Input
                          type="number"
                          min="1"
                          placeholder="1"
                          value={subscriptionInterval || '1'}
                          onChange={(e) => setSubscriptionInterval?.(e.target.value)}
                          className="mt-1"
                        />
                        <p className="text-xs text-muted-foreground mt-1">
                          {__('e.g., 1 = every month, 3 = every 3 months')}
                        </p>
                      </div>
                    </div>
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <Label className="text-xs">{__('Free Trial Days')}</Label>
                        <Input
                          type="number"
                          min="0"
                          placeholder={__('0 = no trial')}
                          value={subscriptionTrialDays || ''}
                          onChange={(e) => setSubscriptionTrialDays?.(e.target.value)}
                          className="mt-1"
                        />
                      </div>
                      <div>
                        <Label className="text-xs">{__('Sign-up Fee')}</Label>
                        <Input
                          type="number"
                          min="0"
                          step="0.01"
                          placeholder="0.00"
                          value={subscriptionSignupFee || ''}
                          onChange={(e) => setSubscriptionSignupFee?.(e.target.value)}
                          className="mt-1"
                        />
                        <p className="text-xs text-muted-foreground mt-1">
                          {__('One-time fee charged on first order')}
                        </p>
                      </div>
                    </div>
                  </div>
                )}
              </>
            )}

            {/* Affiliate option */}
            {isEnabled('affiliate') && setAffiliateEnabled && (
              <>
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="affiliate-enabled"
                    checked={affiliateEnabled || false}
                    onCheckedChange={(checked) => setAffiliateEnabled(checked as boolean)}
                  />
                  <Label htmlFor="affiliate-enabled" className="cursor-pointer font-normal flex items-center gap-1">
                    <Percent className="h-3 w-3" />
                    {__('Enable affiliate commission for this product')}
                  </Label>
                </div>

                {/* Affiliate settings panel */}
                {affiliateEnabled && (
                  <div className="ml-6 p-3 bg-muted/50 rounded-lg space-y-3">
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <Label className="text-xs">{__('Custom Commission Rate (%)')}</Label>
                        <Input
                          type="number"
                          min="0"
                          step="0.01"
                          placeholder={__('Global default')}
                          value={affiliateCommissionRate || ''}
                          onChange={(e) => setAffiliateCommissionRate?.(e.target.value)}
                          className="mt-1"
                        />
                        <p className="text-xs text-muted-foreground mt-1">
                          {__('Leave empty to use the global affiliate commission rate.')}
                        </p>
                      </div>
                    </div>
                  </div>
                )}
              </>
            )}
          </div>
        </div>

        {/* Direct Cart Links - Simple products only */}
        {productId && type === 'simple' && (
          <>
            <Separator />
            <div className="space-y-3">
              <Label>{__('Direct-to-Cart Links')}</Label>
              <p className="text-xs text-muted-foreground">
                {__('Share these links to add this product directly to cart or checkout')}
              </p>
              <div className="flex gap-2">
                <Button
                  type="button"
                  size="sm"
                  variant="outline"
                  onClick={() => copyToClipboard(generateSimpleLink('cart'), 'Cart')}
                  className="flex-1"
                >
                  {copiedLink === generateSimpleLink('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(generateSimpleLink('checkout'), 'Checkout')}
                  className="flex-1"
                >
                  {copiedLink === generateSimpleLink('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 >
  );
}
