import React, { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { __ } from '@/lib/i18n';
import { Button } from '@/components/ui/button';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
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;
};

export function ProductFormTabbed({
  mode,
  initial,
  onSubmit,
  className,
  formRef,
  hideSubmitButton = false,
}: 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);
  const [activeTab, setActiveTab] = useState('general');

  // 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'));
      setActiveTab('general');
      return;
    }

    if (type === 'simple' && !regularPrice) {
      toast.error(__('Regular price is required for simple products'));
      setActiveTab('general');
      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);
    }
  };

  return (
    <form ref={formRef} onSubmit={handleSubmit} className={className}>
      <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
        <TabsList className={`grid w-full mb-6 ${type === 'variable' ? 'grid-cols-4' : 'grid-cols-3'}`}>
          <TabsTrigger value="general" className="flex items-center gap-2">
            <Package className="w-4 h-4" />
            <span className="hidden sm:inline">{__('General')}</span>
          </TabsTrigger>
          <TabsTrigger value="inventory" className="flex items-center gap-2">
            <Layers className="w-4 h-4" />
            <span className="hidden sm:inline">{__('Inventory')}</span>
          </TabsTrigger>
          {type === 'variable' && (
            <TabsTrigger value="variations" className="flex items-center gap-2">
              <Layers className="w-4 h-4" />
              <span className="hidden sm:inline">{__('Variations')}</span>
            </TabsTrigger>
          )}
          <TabsTrigger value="organization" className="flex items-center gap-2">
            <Tag className="w-4 h-4" />
            <span className="hidden sm:inline">{__('Organization')}</span>
          </TabsTrigger>
        </TabsList>

        {/* General Tab */}
        <TabsContent value="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}
            sku={sku}
            setSku={setSku}
            regularPrice={regularPrice}
            setRegularPrice={setRegularPrice}
            salePrice={salePrice}
            setSalePrice={setSalePrice}
          />
        </TabsContent>

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

        {/* Variations Tab */}
        <TabsContent value="variations">
          <VariationsTab
            attributes={attributes}
            setAttributes={setAttributes}
            variations={variations}
            setVariations={setVariations}
            regularPrice={regularPrice}
          />
        </TabsContent>

        {/* Organization Tab */}
        <TabsContent value="organization">
          <OrganizationTab
            categories={categories}
            selectedCategories={selectedCategories}
            setSelectedCategories={setSelectedCategories}
            tags={tags}
            selectedTags={selectedTags}
            setSelectedTags={setSelectedTags}
          />
        </TabsContent>
      </Tabs>

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