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 } 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';

// 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;
};

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 [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);
    }
  }, [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,
      };

      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" /> },
    ...(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}
          />
        </FormSection>

        {/* Inventory Tab */}
        <FormSection id="inventory">
          <InventoryTab
            manageStock={manageStock}
            setManageStock={setManageStock}
            stockQuantity={stockQuantity}
            setStockQuantity={setStockQuantity}
            stockStatus={stockStatus || 'instock'}
            setStockStatus={setStockStatus}
          />
        </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>
  );
}
