/**
 * Product Detail Page
 * View product details with variants
 */

'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useRouter, useParams } from 'next/navigation';
import { productsAPI } from '@/lib/api/products';
import { pricingAPI } from '@/lib/api/pricing';
import { Button, Card, CardHeader, CardTitle, CardContent, Badge, LoadingSpinner, Modal, Input } from '@/components/ui';
import { PRODUCT_TYPES } from '@/lib/utils/constants';
import { formatCurrency, formatDate } from '@/lib/utils/format';
import { ArrowLeft, Edit, Package, Tag, Copy, DollarSign, Plus, Trash2 } from 'lucide-react';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@/components/ui';
import toast from 'react-hot-toast';
import { useState } from 'react';

export default function ProductDetailPage() {
  const router = useRouter();
  const params = useParams();
  const productId = parseInt(params.id);
  const queryClient = useQueryClient();
  const [isCopying, setIsCopying] = useState(false);
  const [showVariantModal, setShowVariantModal] = useState(false);
  const [editingVariant, setEditingVariant] = useState(null);
  const [variantForm, setVariantForm] = useState({ sku: '', attributes: {} });

  // Fetch product details
  const { data, isLoading, error } = useQuery({
    queryKey: ['product', productId],
    queryFn: async () => {
      const response = await productsAPI.getById(productId);
      // API returns { success: true, data: { product } }
      // axios interceptor returns response.data, so response is { success: true, data: { product } }
      return response?.data?.product || null;
    },
  });

  // Fetch default price list
  const { data: defaultPriceList } = useQuery({
    queryKey: ['default-price-list'],
    queryFn: async () => {
      try {
        const response = await pricingAPI.getDefaultPriceList();
        return response?.data?.priceList || response?.data || null;
      } catch (error) {
        return null;
      }
    },
  });

  const product = data;

  // Copy selling_price to default price list
  const copyToPriceListMutation = useMutation({
    mutationFn: async () => {
      if (!defaultPriceList) {
        throw new Error('No default price list found');
      }
      if (!product.selling_price) {
        throw new Error('Product has no selling price to copy');
      }
      return await pricingAPI.createProductPrice({
        price_list_id: defaultPriceList.id,
        product_id: productId,
        variant_id: null,
        price: product.selling_price,
        min_quantity: 1,
        max_quantity: null,
        effective_from: new Date().toISOString(),
        effective_to: null,
        active: true,
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['product', productId]);
      queryClient.invalidateQueries(['price-lists']);
      toast.success('Selling price copied to default price list!');
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to copy to price list';
      toast.error(message);
    },
  });

  const handleCopyToPriceList = async () => {
    setIsCopying(true);
    try {
      await copyToPriceListMutation.mutateAsync();
    } catch (error) {
      // Error handled in mutation
    } finally {
      setIsCopying(false);
    }
  };

  // Variant mutations
  const createVariantMutation = useMutation({
    mutationFn: async (variantData) => {
      return await productsAPI.createVariant(productId, variantData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['product', productId]);
      toast.success('Variant created successfully!');
      setShowVariantModal(false);
      setVariantForm({ sku: '', attributes: {} });
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to create variant';
      toast.error(message);
    },
  });

  const updateVariantMutation = useMutation({
    mutationFn: async ({ variantId, variantData }) => {
      return await productsAPI.updateVariant(productId, variantId, variantData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['product', productId]);
      toast.success('Variant updated successfully!');
      setShowVariantModal(false);
      setEditingVariant(null);
      setVariantForm({ sku: '', attributes: {} });
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to update variant';
      toast.error(message);
    },
  });

  const deleteVariantMutation = useMutation({
    mutationFn: async (variantId) => {
      return await productsAPI.deleteVariant(productId, variantId);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['product', productId]);
      toast.success('Variant deleted successfully!');
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to delete variant';
      toast.error(message);
    },
  });

  const handleDeleteVariant = async (variantId) => {
    if (confirm('Are you sure you want to delete this variant?')) {
      await deleteVariantMutation.mutateAsync(variantId);
    }
  };

  const handleSaveVariant = async () => {
    if (!variantForm.sku || Object.keys(variantForm.attributes).length === 0) {
      toast.error('SKU and at least one attribute are required');
      return;
    }

    if (editingVariant) {
      await updateVariantMutation.mutateAsync({
        variantId: editingVariant.id,
        variantData: variantForm,
      });
    } else {
      await createVariantMutation.mutateAsync(variantForm);
    }
  };

  if (isLoading) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950">
        <div className="flex justify-center py-12">
          <LoadingSpinner size="lg" />
        </div>
      </div>
    );
  }

  if (error || !product) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950">
        <Card>
          <CardContent className="pt-6">
            <div className="text-center py-12">
              <p className="text-red-600 dark:text-red-400 mb-4">
                {error?.response?.data?.message || 'Product not found'}
              </p>
              <Button onClick={() => router.push('/products')} variant="outline">
                Back to Products Hub
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="p-6 bg-gray-50 dark:bg-gray-950 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button
            variant="outline"
            onClick={() => {
              // Navigate back to appropriate page based on product type
              if (data?.product_type === 'RM') {
                router.push('/products/raw-materials');
              } else {
                router.push('/products/finished-goods');
              }
            }}
            className="flex items-center gap-2"
          >
            <ArrowLeft className="w-4 h-4" />
            Back
          </Button>
          <div>
            <h1 className="text-3xl font-bold text-gray-900 dark:text-white">{product.name}</h1>
            <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
              Product Details
            </p>
          </div>
        </div>
        <Button
          variant="primary"
          onClick={() => router.push(`/products/${productId}/edit`)}
          className="flex items-center gap-2"
        >
          <Edit className="w-4 h-4" />
          Edit Product
        </Button>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Main Product Info */}
        <div className="lg:col-span-2 space-y-6">
          {/* Product Information */}
          <Card>
            <CardHeader>
              <CardTitle>Product Information</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm font-medium text-gray-500">SKU</label>
                  <p className="mt-1 font-mono">{product.sku || 'N/A'}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-500">Product Type</label>
                  <div className="mt-1">
                    <Badge variant={product.product_type === 'FG' ? 'success' : 'info'}>
                      {product.product_type === 'FG' ? 'Finished Goods' : 'Raw Materials'}
                    </Badge>
                  </div>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-500">Inventory Tracking</label>
                  <div className="mt-1">
                    {product.track_inventory ? (
                      <Badge variant="success">Tracked</Badge>
                    ) : (
                      <Badge variant="default">Not Tracked</Badge>
                    )}
                  </div>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-500">Selling Price</label>
                  <div className="mt-1 flex items-center gap-2">
                    <p className="font-medium">
                      {product.selling_price ? formatCurrency(product.selling_price) : 'Not set'}
                    </p>
                    {product.selling_price && (
                      <Badge variant="info" className="text-xs">Simple Default</Badge>
                    )}
                  </div>
                  {!product.selling_price && (
                    <p className="text-xs text-gray-400 mt-1">Set in product edit or use price lists</p>
                  )}
                </div>
              </div>

              {product.description && (
                <div>
                  <label className="text-sm font-medium text-gray-500">Description</label>
                  <p className="mt-1 text-gray-900 dark:text-white">{product.description}</p>
                </div>
              )}

              <div className="grid grid-cols-2 gap-4 pt-4 border-t">
                <div>
                  <label className="text-sm font-medium text-gray-500">Created</label>
                  <p className="mt-1 text-sm text-gray-600">{formatDate(product.created_at)}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-500">Last Updated</label>
                  <p className="mt-1 text-sm text-gray-600">{formatDate(product.updated_at)}</p>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Product Image */}
          {product.image_url && (
            <Card>
              <CardHeader>
                <CardTitle>Product Image</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex justify-center">
                  <img
                    src={product.image_url}
                    alt={product.name}
                    className="max-w-md rounded-lg shadow-lg"
                  />
                </div>
              </CardContent>
            </Card>
          )}

          {/* Variants */}
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle>Product Variants</CardTitle>
                <Button
                  variant="primary"
                  size="sm"
                  onClick={() => {
                    setEditingVariant(null);
                    setVariantForm({ sku: '', attributes: {} });
                    setShowVariantModal(true);
                  }}
                  className="flex items-center gap-2"
                >
                  <Plus className="w-4 h-4" />
                  Add Variant
                </Button>
              </div>
            </CardHeader>
            <CardContent>
              {product.variants && product.variants.length > 0 ? (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>SKU</TableHead>
                      <TableHead>Attributes</TableHead>
                      <TableHead>Created</TableHead>
                      <TableHead align="right">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {product.variants.map((variant) => (
                      <TableRow key={variant.id}>
                        <TableCell>
                          <span className="font-mono text-sm">{variant.sku || 'N/A'}</span>
                        </TableCell>
                        <TableCell>
                          {variant.attributes && Object.keys(variant.attributes).length > 0 ? (
                            <div className="flex flex-wrap gap-2">
                              {Object.entries(variant.attributes).map(([key, value]) => (
                                <Badge key={key} variant="info">
                                  {key}: {value}
                                </Badge>
                              ))}
                            </div>
                          ) : (
                            <span className="text-gray-400">No attributes</span>
                          )}
                        </TableCell>
                        <TableCell>
                          <span className="text-sm text-gray-600">
                            {formatDate(variant.created_at)}
                          </span>
                        </TableCell>
                        <TableCell align="right">
                          <div className="flex justify-end gap-2">
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => {
                                setEditingVariant(variant);
                                setVariantForm({
                                  sku: variant.sku || '',
                                  attributes: variant.attributes || {},
                                });
                                setShowVariantModal(true);
                              }}
                            >
                              <Edit className="w-4 h-4" />
                            </Button>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => handleDeleteVariant(variant.id)}
                              className="text-red-600 hover:text-red-700"
                            >
                              <Trash2 className="w-4 h-4" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              ) : (
                <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                  <Package className="w-12 h-12 mx-auto mb-4 opacity-50" />
                  <p>No variants yet</p>
                  <Button
                    variant="primary"
                    size="sm"
                    onClick={() => {
                      setEditingVariant(null);
                      setVariantForm({ sku: '', attributes: {} });
                      setShowVariantModal(true);
                    }}
                    className="mt-4"
                  >
                    <Plus className="w-4 h-4 mr-2" />
                    Add First Variant
                  </Button>
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Quick Info */}
          <Card>
            <CardHeader>
              <CardTitle>Quick Info</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center gap-3">
                <Package className="w-5 h-5 text-gray-400" />
                <div>
                  <p className="text-sm text-gray-500">Product ID</p>
                  <p className="font-medium">{product.id}</p>
                </div>
              </div>
              {product.selling_price && defaultPriceList && (
                <div className="pt-4 border-t">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={handleCopyToPriceList}
                    disabled={isCopying}
                    loading={isCopying}
                    className="w-full flex items-center justify-center gap-2"
                  >
                    <Copy className="w-4 h-4" />
                    Copy Selling Price to Default Price List
                  </Button>
                  <p className="text-xs text-gray-500 dark:text-gray-400 mt-2 text-center">
                    Creates a price entry in "{defaultPriceList.name}"
                  </p>
                </div>
              )}
            </CardContent>
          </Card>

          {/* Pricing Actions */}
          {product.selling_price && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <DollarSign className="w-5 h-5" />
                  Pricing
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400 mb-2">
                    Quick Actions:
                  </p>
                  <div className="flex flex-col gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => router.push('/pricing')}
                      className="w-full"
                    >
                      Manage Price Lists
                    </Button>
                    {defaultPriceList && (
                      <Button
                        variant="primary"
                        size="sm"
                        onClick={handleCopyToPriceList}
                        disabled={isCopying}
                        loading={isCopying}
                        className="w-full flex items-center justify-center gap-2"
                      >
                        <Copy className="w-4 h-4" />
                        Add to Default Price List
                      </Button>
                    )}
                  </div>
                </div>
                <div className="text-xs text-gray-500 dark:text-gray-400 pt-2 border-t">
                  <p className="font-medium mb-1">Price List Benefits:</p>
                  <ul className="list-disc list-inside space-y-1">
                    <li>Seasonal/holiday pricing (Valentine's, Easter, Black Friday, Christmas)</li>
                    <li>Date-based pricing with effective dates</li>
                    <li>Quantity-based pricing tiers</li>
                    <li>Customer-specific pricing</li>
                  </ul>
                </div>
              </CardContent>
            </Card>
          )}
        </div>
      </div>

      {/* Variant Modal */}
      <Modal
        isOpen={showVariantModal}
        onClose={() => {
          setShowVariantModal(false);
          setEditingVariant(null);
          setVariantForm({ sku: '', attributes: {} });
        }}
        title={editingVariant ? 'Edit Variant' : 'Add Variant'}
      >
        <div className="space-y-4">
          <Input
            label="Variant SKU"
            type="text"
            placeholder="e.g., PRODUCT-001-M-BLUE"
            value={variantForm.sku}
            onChange={(e) => setVariantForm({ ...variantForm, sku: e.target.value })}
          />

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Attributes (e.g., Size, Color)
            </label>
            <div className="space-y-2">
              {Object.entries(variantForm.attributes || {}).map(([key, value], index) => (
                <div key={index} className="flex gap-2">
                  <Input
                    type="text"
                    placeholder="Attribute name (e.g., Size)"
                    value={key}
                    onChange={(e) => {
                      const newAttributes = { ...variantForm.attributes };
                      delete newAttributes[key];
                      newAttributes[e.target.value] = value;
                      setVariantForm({ ...variantForm, attributes: newAttributes });
                    }}
                  />
                  <Input
                    type="text"
                    placeholder="Value (e.g., M)"
                    value={value}
                    onChange={(e) => {
                      setVariantForm({
                        ...variantForm,
                        attributes: { ...variantForm.attributes, [key]: e.target.value },
                      });
                    }}
                  />
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      const newAttributes = { ...variantForm.attributes };
                      delete newAttributes[key];
                      setVariantForm({ ...variantForm, attributes: newAttributes });
                    }}
                  >
                    <Trash2 className="w-4 h-4" />
                  </Button>
                </div>
              ))}
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  setVariantForm({
                    ...variantForm,
                    attributes: { ...variantForm.attributes, '': '' },
                  });
                }}
                className="w-full"
              >
                <Plus className="w-4 h-4 mr-2" />
                Add Attribute
              </Button>
            </div>
            <p className="mt-2 text-xs text-gray-500 dark:text-gray-400">
              Example: Size = M, Color = Blue
            </p>
          </div>

          <div className="flex justify-end gap-2 pt-4 border-t">
            <Button
              variant="outline"
              onClick={() => {
                setShowVariantModal(false);
                setEditingVariant(null);
                setVariantForm({ sku: '', attributes: {} });
              }}
            >
              Cancel
            </Button>
            <Button
              variant="primary"
              onClick={handleSaveVariant}
              loading={createVariantMutation.isLoading || updateVariantMutation.isLoading}
            >
              {editingVariant ? 'Update' : 'Create'} Variant
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  );
}

