import React, { useState, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { __ } from '@/lib/i18n';
import { Button } from '@/components/ui/button';
import { VerticalTabForm, FormSection } from '@/components/VerticalTabForm';
import { Package, DollarSign, Layers, Tag, Download } from 'lucide-react';
import { toast } from 'sonner';
import { GeneralTab } from './tabs/GeneralTab';
import { InventoryTab } from './tabs/InventoryTab';
import { VariationsTab, ProductVariant } from './tabs/VariationsTab';
import { OrganizationTab } from './tabs/OrganizationTab';
import { DownloadsTab, DownloadableFile } from './tabs/DownloadsTab';

// Types
export type ProductFormData = {
  name: string;
  type: 'simple' | 'variable' | 'grouped' | 'external';
  status: 'publish' | 'draft' | 'pending' | 'private';
  description?: string;
  short_description?: string;
  sku?: string;
  regular_price?: string;
  sale_price?: string;
  manage_stock?: boolean;
  stock_quantity?: number;
  stock_status?: 'instock' | 'outofstock' | 'onbackorder';
  categories?: number[];
  tags?: number[];
  images?: string[];
  attributes?: Array<{ name: string; options: string[]; variation: boolean }>;
  variations?: ProductVariant[];
  virtual?: boolean;
  downloadable?: boolean;
  featured?: boolean;
  downloads?: DownloadableFile[];
  download_limit?: string;
  download_expiry?: string;
  // Licensing
  licensing_enabled?: boolean;
  license_activation_limit?: string;
  license_duration_days?: string;
  license_activation_method?: '' | 'api' | 'oauth';
  // Subscription
  subscription_enabled?: boolean;
  subscription_period?: 'day' | 'week' | 'month' | 'year';
  subscription_interval?: string;
  subscription_trial_days?: string;
  subscription_signup_fee?: string;
  // Affiliate
  affiliate_enabled?: boolean;
  affiliate_commission_rate?: string;
};

type Props = {
  mode: 'create' | 'edit';
  initial?: ProductFormData | null;
  onSubmit: (data: ProductFormData) => Promise<void> | void;
  className?: string;
  formRef?: React.RefObject<HTMLFormElement>;
  hideSubmitButton?: boolean;
  productId?: number;
};

export function ProductFormTabbed({
  mode,
  initial,
  onSubmit,
  className,
  formRef,
  hideSubmitButton = false,
  productId,
}: Props) {
  // Form state
  const [name, setName] = useState(initial?.name || '');
  const [type, setType] = useState<ProductFormData['type']>(initial?.type || 'simple');
  const [status, setStatus] = useState<ProductFormData['status']>(initial?.status || 'publish');
  const [description, setDescription] = useState(initial?.description || '');
  const [shortDescription, setShortDescription] = useState(initial?.short_description || '');
  const [sku, setSku] = useState(initial?.sku || '');
  const [regularPrice, setRegularPrice] = useState(initial?.regular_price || '');
  const [salePrice, setSalePrice] = useState(initial?.sale_price || '');
  const [manageStock, setManageStock] = useState(initial?.manage_stock || false);
  const [stockQuantity, setStockQuantity] = useState(initial?.stock_quantity?.toString() || '');
  const [stockStatus, setStockStatus] = useState<ProductFormData['stock_status']>(initial?.stock_status || 'instock');
  const [selectedCategories, setSelectedCategories] = useState<number[]>(initial?.categories || []);
  const [selectedTags, setSelectedTags] = useState<number[]>(initial?.tags || []);
  const [images, setImages] = useState<string[]>(initial?.images || []);
  const [attributes, setAttributes] = useState<Array<{ name: string; options: string[]; variation: boolean }>>(
    initial?.attributes || []
  );
  const [variations, setVariations] = useState<ProductVariant[]>(initial?.variations || []);
  const [virtual, setVirtual] = useState(initial?.virtual || false);
  const [downloadable, setDownloadable] = useState(initial?.downloadable || false);
  const [featured, setFeatured] = useState(initial?.featured || false);
  const [downloads, setDownloads] = useState<DownloadableFile[]>(initial?.downloads || []);
  const [downloadLimit, setDownloadLimit] = useState(initial?.download_limit || '');
  const [downloadExpiry, setDownloadExpiry] = useState(initial?.download_expiry || '');
  const [licensingEnabled, setLicensingEnabled] = useState(initial?.licensing_enabled || false);
  const [licenseActivationLimit, setLicenseActivationLimit] = useState(initial?.license_activation_limit || '');
  const [licenseDurationDays, setLicenseDurationDays] = useState(initial?.license_duration_days || '');
  const [licenseActivationMethod, setLicenseActivationMethod] = useState<'' | 'api' | 'oauth'>(initial?.license_activation_method || '');
  // Subscription state
  const [subscriptionEnabled, setSubscriptionEnabled] = useState(initial?.subscription_enabled || false);
  const [subscriptionPeriod, setSubscriptionPeriod] = useState<'day' | 'week' | 'month' | 'year'>(initial?.subscription_period || 'month');
  const [subscriptionInterval, setSubscriptionInterval] = useState(initial?.subscription_interval || '1');
  const [subscriptionTrialDays, setSubscriptionTrialDays] = useState(initial?.subscription_trial_days || '');
  const [subscriptionSignupFee, setSubscriptionSignupFee] = useState(initial?.subscription_signup_fee || '');
  // Affiliate state
  const [affiliateEnabled, setAffiliateEnabled] = useState(initial?.affiliate_enabled || false);
  const [affiliateCommissionRate, setAffiliateCommissionRate] = useState(initial?.affiliate_commission_rate || '');
  const [submitting, setSubmitting] = useState(false);

  // Update form state when initial data changes (for edit mode)
  useEffect(() => {
    if (initial && mode === 'edit') {
      setName(initial.name || '');
      setType(initial.type || 'simple');
      setStatus(initial.status || 'publish');
      setDescription(initial.description || '');
      setShortDescription(initial.short_description || '');
      setSku(initial.sku || '');
      setRegularPrice(initial.regular_price || '');
      setSalePrice(initial.sale_price || '');
      setManageStock(initial.manage_stock || false);
      setStockQuantity(initial.stock_quantity?.toString() || '');
      setStockStatus(initial.stock_status || 'instock');
      setSelectedCategories(initial.categories || []);
      setSelectedTags(initial.tags || []);
      setImages(initial.images || []);
      setAttributes(initial.attributes || []);
      setVariations(initial.variations || []);
      setVirtual(initial.virtual || false);
      setDownloadable(initial.downloadable || false);
      setFeatured(initial.featured || false);
      setDownloads(initial.downloads || []);
      setDownloadLimit(initial.download_limit || '');
      setDownloadExpiry(initial.download_expiry || '');
      setLicensingEnabled(initial.licensing_enabled || false);
      setLicenseActivationLimit(initial.license_activation_limit || '');
      setLicenseDurationDays(initial.license_duration_days || '');
      setLicenseActivationMethod(initial.license_activation_method || '');
      // Subscription
      setSubscriptionEnabled(initial.subscription_enabled || false);
      setSubscriptionPeriod(initial.subscription_period || 'month');
      setSubscriptionInterval(initial.subscription_interval || '1');
      setSubscriptionTrialDays(initial.subscription_trial_days || '');
      setSubscriptionSignupFee(initial.subscription_signup_fee || '');
      // Affiliate
      setAffiliateEnabled(initial.affiliate_enabled || false);
      setAffiliateCommissionRate(initial.affiliate_commission_rate || '');
    }
  }, [initial, mode]);

  // Fetch categories
  const categoriesQ = useQuery({
    queryKey: ['product-categories'],
    queryFn: () => api.get('/products/categories'),
  });

  // Fetch tags
  const tagsQ = useQuery({
    queryKey: ['product-tags'],
    queryFn: () => api.get('/products/tags'),
  });

  const categories = categoriesQ.data || [];
  const tags = tagsQ.data || [];

  // Handle form submission
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (submitting) return;

    // Validation
    if (!name.trim()) {
      toast.error(__('Product name is required'));
      return;
    }

    if (type === 'simple' && !regularPrice) {
      toast.error(__('Regular price is required for simple products'));
      return;
    }

    setSubmitting(true);
    try {
      const payload: ProductFormData = {
        name: name.trim(),
        type,
        status,
        description,
        short_description: shortDescription,
        sku,
        regular_price: regularPrice,
        sale_price: salePrice,
        manage_stock: manageStock,
        stock_quantity: manageStock ? parseInt(stockQuantity) || 0 : undefined,
        stock_status: stockStatus,
        categories: selectedCategories,
        tags: selectedTags,
        images,
        attributes: type === 'variable' ? attributes : undefined,
        variations: type === 'variable' ? variations : undefined,
        virtual,
        downloadable,
        featured,
        downloads: downloadable ? downloads : undefined,
        download_limit: downloadable ? downloadLimit : undefined,
        download_expiry: downloadable ? downloadExpiry : undefined,
        licensing_enabled: licensingEnabled,
        license_activation_limit: licensingEnabled ? licenseActivationLimit : undefined,
        license_duration_days: licensingEnabled ? licenseDurationDays : undefined,
        license_activation_method: licensingEnabled ? licenseActivationMethod : undefined,
        // Subscription
        subscription_enabled: subscriptionEnabled,
        subscription_period: subscriptionEnabled ? subscriptionPeriod : undefined,
        subscription_interval: subscriptionEnabled ? subscriptionInterval : undefined,
        subscription_trial_days: subscriptionEnabled ? subscriptionTrialDays : undefined,
        subscription_signup_fee: subscriptionEnabled ? subscriptionSignupFee : undefined,
        // Affiliate
        affiliate_enabled: affiliateEnabled,
        affiliate_commission_rate: affiliateEnabled ? affiliateCommissionRate : undefined,
      };

      await onSubmit(payload);
    } catch (error: any) {
      toast.error(error.message || __('Failed to save product'));
    } finally {
      setSubmitting(false);
    }
  };

  // Define tabs based on product type
  const tabs = [
    { id: 'general', label: __('General'), icon: <Package className="w-4 h-4" /> },
    { id: 'inventory', label: __('Inventory'), icon: <Layers className="w-4 h-4" /> },
    ...(downloadable ? [{ id: 'downloads', label: __('Downloads'), icon: <Download className="w-4 h-4" /> }] : []),
    ...(type === 'variable' ? [{ id: 'variations', label: __('Variations'), icon: <Layers className="w-4 h-4" /> }] : []),
    { id: 'organization', label: __('Organization'), icon: <Tag className="w-4 h-4" /> },
  ];

  return (
    <form ref={formRef} onSubmit={handleSubmit} className={className}>
      <VerticalTabForm tabs={tabs}>
        {/* General Tab */}
        <FormSection id="general">
          <GeneralTab
            name={name}
            setName={setName}
            type={type}
            setType={setType}
            status={status}
            setStatus={setStatus}
            description={description}
            setDescription={setDescription}
            shortDescription={shortDescription}
            setShortDescription={setShortDescription}
            virtual={virtual}
            setVirtual={setVirtual}
            downloadable={downloadable}
            setDownloadable={setDownloadable}
            featured={featured}
            setFeatured={setFeatured}
            images={images}
            setImages={setImages}
            sku={sku}
            setSku={setSku}
            regularPrice={regularPrice}
            setRegularPrice={setRegularPrice}
            salePrice={salePrice}
            setSalePrice={setSalePrice}
            productId={productId}
            licensingEnabled={licensingEnabled}
            setLicensingEnabled={setLicensingEnabled}
            licenseActivationLimit={licenseActivationLimit}
            setLicenseActivationLimit={setLicenseActivationLimit}
            licenseDurationDays={licenseDurationDays}
            setLicenseDurationDays={setLicenseDurationDays}
            licenseActivationMethod={licenseActivationMethod}
            setLicenseActivationMethod={setLicenseActivationMethod}
            subscriptionEnabled={subscriptionEnabled}
            setSubscriptionEnabled={setSubscriptionEnabled}
            subscriptionPeriod={subscriptionPeriod}
            setSubscriptionPeriod={setSubscriptionPeriod}
            subscriptionInterval={subscriptionInterval}
            setSubscriptionInterval={setSubscriptionInterval}
            subscriptionTrialDays={subscriptionTrialDays}
            setSubscriptionTrialDays={setSubscriptionTrialDays}
            subscriptionSignupFee={subscriptionSignupFee}
            setSubscriptionSignupFee={setSubscriptionSignupFee}
            affiliateEnabled={affiliateEnabled}
            setAffiliateEnabled={setAffiliateEnabled}
            affiliateCommissionRate={affiliateCommissionRate}
            setAffiliateCommissionRate={setAffiliateCommissionRate}
          />
        </FormSection>

        {/* Inventory Tab */}
        <FormSection id="inventory">
          <InventoryTab
            manageStock={manageStock}
            setManageStock={setManageStock}
            stockQuantity={stockQuantity}
            setStockQuantity={setStockQuantity}
            stockStatus={stockStatus || 'instock'}
            setStockStatus={setStockStatus}
          />
        </FormSection>

        {/* Downloads Tab (only for downloadable products) */}
        {downloadable && (
          <FormSection id="downloads">
            <DownloadsTab
              downloads={downloads}
              setDownloads={setDownloads}
              downloadLimit={downloadLimit}
              setDownloadLimit={setDownloadLimit}
              downloadExpiry={downloadExpiry}
              setDownloadExpiry={setDownloadExpiry}
            />
          </FormSection>
        )}

        {/* Variations Tab (only for variable products) */}
        {type === 'variable' && (
          <FormSection id="variations">
            <VariationsTab
              attributes={attributes}
              setAttributes={setAttributes}
              variations={variations}
              setVariations={setVariations}
              regularPrice={regularPrice}
              productId={productId}
            />
          </FormSection>
        )}

        {/* Organization Tab */}
        <FormSection id="organization">
          <OrganizationTab
            categories={categories}
            selectedCategories={selectedCategories}
            setSelectedCategories={setSelectedCategories}
            tags={tags}
            selectedTags={selectedTags}
            setSelectedTags={setSelectedTags}
          />
        </FormSection>

        {/* Submit Button */}
        {!hideSubmitButton && (
          <div className="mt-6 flex gap-3">
            <Button type="submit" disabled={submitting}>
              {submitting
                ? __('Saving...')
                : mode === 'create'
                  ? __('Create Product')
                  : __('Update Product')}
            </Button>
          </div>
        )}
      </VerticalTabForm>
    </form>
  );
}
