/**
 * Discount Detail Page
 * View discount details
 */

'use client';

import { useParams, useRouter } from 'next/navigation';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { discountsAPI } from '@/lib/api/discounts';
import {
  Button,
  Card,
  CardHeader,
  CardTitle,
  CardContent,
  Badge,
  LoadingPage,
  Modal,
} from '@/components/ui';
import { formatCurrency, formatDate, formatDateTime } from '@/lib/utils/format';
import { ArrowLeft, Edit, Trash2, Plus } from 'lucide-react';
import toast from 'react-hot-toast';
import { useState } from 'react';
import { Input, Select } from '@/components/ui';
import { productsAPI } from '@/lib/api/products';
import { categoriesAPI } from '@/lib/api/categories';

export default function DiscountDetailPage() {
  const router = useRouter();
  const params = useParams();
  const discountId = parseInt(params.id);
  const queryClient = useQueryClient();
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [showAddRuleModal, setShowAddRuleModal] = useState(false);
  const [newRule, setNewRule] = useState({
    rule_type: 'ALL',
    product_id: '',
    category_id: '',
    min_quantity: 1,
  });

  // Fetch discount details
  const { data: discount, isLoading, error } = useQuery({
    queryKey: ['discount', discountId],
    queryFn: async () => {
      if (isNaN(discountId)) {
        throw new Error('Invalid discount ID');
      }
      const response = await discountsAPI.getById(discountId);
      return response?.data || response;
    },
    enabled: !isNaN(discountId),
  });

  const deleteDiscountMutation = useMutation({
    mutationFn: async () => {
      return await discountsAPI.delete(discountId);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['discounts']);
      toast.success('Discount deleted successfully!');
      router.push('/discounts');
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to delete discount';
      toast.error(message);
      setShowDeleteModal(false);
    },
  });

  const handleDelete = () => {
    deleteDiscountMutation.mutate();
  };

  // Fetch products and categories for rule creation
  // Enable queries immediately so data is ready when modal opens
  const { data: productsData, isLoading: isLoadingProducts, error: productsError } = useQuery({
    queryKey: ['products', 'FG', 'discount-rules'],
    queryFn: async () => {
      try {
        // Only fetch FG products since discounts apply to finished goods
        // API has max limit of 100, so we fetch the maximum allowed
        // API client interceptor returns axios response.data
        // Server returns: { success: true, data: { products: [...], pagination: {...} } }
        // axios response = { data: { success: true, data: { products: [...] } } }
        // After interceptor: response = { success: true, data: { products: [...] } }
        const response = await productsAPI.list({ product_type: 'FG', limit: 100 });
        
        // Extract products from response structure
        // Response is: { success: true, data: { products: [...], pagination: {...} } }
        const products = response?.data?.products || [];
        
        if (!Array.isArray(products)) {
          console.warn('[Discount Rules] Products is not an array:', { response, products });
          return [];
        }
        
        return products;
      } catch (error) {
        console.error('[Discount Rules] Error fetching products:', error);
        return [];
      }
    },
    enabled: true, // Always enabled so data is ready
    staleTime: 5 * 60 * 1000, // Cache for 5 minutes
  });

  const { data: categoriesData, isLoading: isLoadingCategories, error: categoriesError } = useQuery({
    queryKey: ['categories', 'all', 'discount-rules'],
    queryFn: async () => {
      try {
        // API has max limit of 100, so we fetch the maximum allowed
        // API client interceptor returns axios response.data
        // Server returns: { success: true, data: { categories: [...], pagination: {...} } }
        // axios response = { data: { success: true, data: { categories: [...] } } }
        // After interceptor: response = { success: true, data: { categories: [...] } }
        const response = await categoriesAPI.list({ limit: 100 });
        
        // Extract categories from response structure
        // Response is: { success: true, data: { categories: [...], pagination: {...} } }
        const categories = response?.data?.categories || [];
        
        if (!Array.isArray(categories)) {
          console.warn('[Discount Rules] Categories is not an array:', { response, categories });
          return [];
        }
        
        return categories;
      } catch (error) {
        console.error('[Discount Rules] Error fetching categories:', error);
        return [];
      }
    },
    enabled: true, // Always enabled so data is ready
    staleTime: 5 * 60 * 1000, // Cache for 5 minutes
  });

  const products = Array.isArray(productsData) ? productsData : [];
  const categories = Array.isArray(categoriesData) ? categoriesData : [];

  // Create discount rule mutation
  const createRuleMutation = useMutation({
    mutationFn: async (ruleData) => {
      return await discountsAPI.createRule(discountId, ruleData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['discount', discountId]);
      toast.success('Discount rule created successfully!');
      setShowAddRuleModal(false);
      setNewRule({ rule_type: 'ALL', product_id: '', category_id: '', min_quantity: 1 });
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to create discount rule';
      toast.error(message);
    },
  });

  // Delete discount rule mutation
  const deleteRuleMutation = useMutation({
    mutationFn: async (ruleId) => {
      return await discountsAPI.deleteRule(discountId, ruleId);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['discount', discountId]);
      toast.success('Discount rule deleted successfully!');
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to delete discount rule';
      toast.error(message);
    },
  });

  const handleCreateRule = () => {
    const ruleData = {
      rule_type: newRule.rule_type,
      min_quantity: parseFloat(newRule.min_quantity) || 1,
      ...(newRule.rule_type === 'PRODUCT' && { product_id: parseInt(newRule.product_id) }),
      ...(newRule.rule_type === 'CATEGORY' && { category_id: parseInt(newRule.category_id) }),
    };

    createRuleMutation.mutate(ruleData);
  };

  const handleDeleteRule = (ruleId) => {
    if (confirm('Are you sure you want to delete this discount rule?')) {
      deleteRuleMutation.mutate(ruleId);
    }
  };

  const getRuleDisplayName = (rule) => {
    switch (rule.rule_type) {
      case 'ALL':
        return 'All Products';
      case 'PRODUCT':
        const product = rule.product || products.find(p => p.id === rule.product_id);
        return product ? `Product: ${product.name}` : `Product ID: ${rule.product_id}`;
      case 'CATEGORY':
        const category = rule.category || categories.find(c => c.id === rule.category_id);
        return category ? `Category: ${category.name}` : `Category ID: ${rule.category_id}`;
      default:
        return rule.rule_type;
    }
  };

  if (isLoading) {
    return <LoadingPage message="Loading discount details..." />;
  }

  if (error) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950 text-center text-red-600">
        <p>Error: {error.message}</p>
        <Button onClick={() => router.back()} className="mt-4">
          Go Back
        </Button>
      </div>
    );
  }

  if (!discount) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950 text-center text-gray-600">
        <p>Discount not found.</p>
        <Button onClick={() => router.back()} className="mt-4">
          Go Back
        </Button>
      </div>
    );
  }

  const getDiscountTypeLabel = (type) => {
    switch (type) {
      case 'PERCENTAGE':
        return 'Percentage';
      case 'FIXED_AMOUNT':
        return 'Fixed Amount';
      case 'BUY_X_GET_Y':
        return 'Buy X Get Y';
      default:
        return type;
    }
  };

  const formatDiscountValue = (discount) => {
    if (discount.discount_type === 'PERCENTAGE') {
      return `${discount.discount_value}%`;
    } else if (discount.discount_type === 'FIXED_AMOUNT') {
      return formatCurrency(discount.discount_value);
    } else if (discount.discount_type === 'BUY_X_GET_Y') {
      return `Buy ${discount.buy_quantity || 'X'} Get ${discount.discount_value || 'Y'}`;
    }
    return discount.discount_value || 'N/A';
  };

  return (
    <div className="container mx-auto p-6">
      <div className="flex justify-between items-center mb-6">
        <Button variant="ghost" onClick={() => router.back()} className="flex items-center">
          <ArrowLeft className="w-4 h-4 mr-2" /> Back to Discounts
        </Button>
        <div className="flex gap-2">
          <Button
            variant="outline"
            onClick={() => router.push(`/discounts/${discountId}/edit`)}
            className="flex items-center gap-2"
          >
            <Edit className="w-4 h-4" />
            Edit
          </Button>
          <Button
            variant="outline"
            onClick={() => setShowDeleteModal(true)}
            className="flex items-center gap-2 text-red-600 hover:text-red-700"
          >
            <Trash2 className="w-4 h-4" />
            Delete
          </Button>
        </div>
      </div>

      <Card className="mb-6">
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <span>{discount.name}</span>
            {discount.active ? (
              <Badge variant="success">Active</Badge>
            ) : (
              <Badge variant="default">Inactive</Badge>
            )}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <h3 className="font-semibold text-gray-700 mb-3">Discount Information</h3>
              {discount.code && (
                <p className="text-gray-600 mb-2">
                  <span className="font-medium">Code:</span>{' '}
                  <span className="font-mono">{discount.code}</span>
                </p>
              )}
              <p className="text-gray-600 mb-2">
                <span className="font-medium">Type:</span>{' '}
                <Badge variant="info">{getDiscountTypeLabel(discount.discount_type)}</Badge>
              </p>
              <p className="text-gray-600 mb-2">
                <span className="font-medium">Value:</span>{' '}
                <span className="text-lg font-bold">{formatDiscountValue(discount)}</span>
              </p>
              {discount.description && (
                <p className="text-gray-600 mb-2">
                  <span className="font-medium">Description:</span> {discount.description}
                </p>
              )}
            </div>
            <div>
              <h3 className="font-semibold text-gray-700 mb-3">Terms & Conditions</h3>
              <p className="text-gray-600 mb-2">
                <span className="font-medium">Minimum Purchase:</span>{' '}
                {formatCurrency(discount.min_purchase_amount || 0)}
              </p>
              {discount.max_discount_amount && (
                <p className="text-gray-600 mb-2">
                  <span className="font-medium">Max Discount:</span>{' '}
                  {formatCurrency(discount.max_discount_amount)}
                </p>
              )}
              <p className="text-gray-600 mb-2">
                <span className="font-medium">Effective From:</span>{' '}
                {formatDate(discount.effective_from)}
              </p>
              {discount.effective_to ? (
                <p className="text-gray-600 mb-2">
                  <span className="font-medium">Effective To:</span>{' '}
                  {formatDate(discount.effective_to)}
                </p>
              ) : (
                <p className="text-gray-600 mb-2">
                  <span className="font-medium">Expiration:</span> No expiration
                </p>
              )}
              {discount.max_uses_per_customer && (
                <p className="text-gray-600 mb-2">
                  <span className="font-medium">Max Uses Per Customer:</span>{' '}
                  {discount.max_uses_per_customer}
                </p>
              )}
              {discount.max_total_uses && (
                <p className="text-gray-600 mb-2">
                  <span className="font-medium">Max Total Uses:</span> {discount.max_total_uses}
                </p>
              )}
            </div>
          </div>
          <div className="mt-6 pt-6 border-t">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <p className="text-sm text-gray-600">Usage Count</p>
                <p className="text-2xl font-bold text-gray-900">{discount.usage_count || 0}</p>
              </div>
              <div>
                <p className="text-sm text-gray-600">Created At</p>
                <p className="text-sm text-gray-900">{formatDateTime(discount.created_at)}</p>
              </div>
              <div>
                <p className="text-sm text-gray-600">Last Updated</p>
                <p className="text-sm text-gray-900">{formatDateTime(discount.updated_at)}</p>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Discount Rules Section */}
      <Card>
        <CardHeader>
          <div className="flex justify-between items-center">
            <CardTitle>Discount Rules</CardTitle>
            <Button
              variant="primary"
              size="sm"
              onClick={() => setShowAddRuleModal(true)}
              className="flex items-center gap-2"
            >
              <Plus className="w-4 h-4" />
              Add Rule
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {discount.rules && discount.rules.length > 0 ? (
            <div className="space-y-3">
              {discount.rules.map((rule) => (
                <div key={rule.id} className="p-4 border border-gray-200 dark:border-gray-700 rounded-lg">
                  <div className="flex justify-between items-start">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <Badge variant="info">{rule.rule_type}</Badge>
                        {rule.min_quantity > 1 && (
                          <span className="text-sm text-gray-600">
                            Min Quantity: {rule.min_quantity}
                          </span>
                        )}
                      </div>
                      <p className="font-medium text-gray-900 dark:text-white">
                        {getRuleDisplayName(rule)}
                      </p>
                    </div>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleDeleteRule(rule.id)}
                      className="text-red-600 hover:text-red-700 hover:bg-red-50"
                      disabled={deleteRuleMutation.isLoading}
                    >
                      <Trash2 className="w-4 h-4" />
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-8 text-gray-500">
              <p>No discount rules. Add a rule to assign this discount to specific products or categories.</p>
              <p className="text-sm mt-2">If no rules are added, the discount applies to all products.</p>
            </div>
          )}
        </CardContent>
      </Card>

      <Modal
        isOpen={showDeleteModal}
        onClose={() => setShowDeleteModal(false)}
        title="Delete Discount"
        description={`Are you sure you want to delete "${discount.name}"? This action cannot be undone.`}
      >
        <div className="flex justify-end gap-4 mt-6">
          <Button variant="outline" onClick={() => setShowDeleteModal(false)}>
            Cancel
          </Button>
          <Button
            variant="primary"
            onClick={handleDelete}
            disabled={deleteDiscountMutation.isLoading}
            loading={deleteDiscountMutation.isLoading}
            className="bg-red-600 hover:bg-red-700"
          >
            Delete
          </Button>
        </div>
      </Modal>

      {/* Add Rule Modal */}
      <Modal
        isOpen={showAddRuleModal}
        onClose={() => {
          setShowAddRuleModal(false);
          setNewRule({ rule_type: 'ALL', product_id: '', category_id: '', min_quantity: 1 });
        }}
        title="Add Discount Rule"
        description="Assign this discount to specific products, categories, or all products"
      >
        <div className="space-y-4 mt-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Rule Type <span className="text-red-500">*</span>
            </label>
            <Select
              value={newRule.rule_type}
              onChange={(e) => setNewRule({ ...newRule, rule_type: e.target.value, product_id: '', category_id: '' })}
              options={[
                { value: 'ALL', label: 'All Products' },
                { value: 'PRODUCT', label: 'Specific Product' },
                { value: 'CATEGORY', label: 'Product Category' },
              ]}
            />
          </div>

          {newRule.rule_type === 'PRODUCT' && (
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                Product (FG) <span className="text-red-500">*</span>
                {isLoadingProducts && <span className="ml-2 text-xs text-gray-500">(Loading...)</span>}
              </label>
              {isLoadingProducts ? (
                <div className="w-full px-3 py-2 border border-gray-300 rounded-lg bg-gray-50 text-gray-500">
                  Loading products...
                </div>
              ) : productsError ? (
                <div className="w-full px-3 py-2 border border-red-300 rounded-lg bg-red-50 text-red-600">
                  Error loading products: {productsError.message || 'Unknown error'}
                </div>
              ) : products.length === 0 ? (
                <div className="w-full px-3 py-2 border border-red-300 rounded-lg bg-red-50 text-red-600">
                  No finished goods products found. Please create FG products first.
                </div>
              ) : (
                <select
                  value={newRule.product_id}
                  onChange={(e) => setNewRule({ ...newRule, product_id: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                  required
                >
                  <option value="">-- Select Product ({products.length} available) --</option>
                  {products.map((product) => (
                    <option key={product.id} value={product.id}>
                      {product.name} {product.sku ? `(${product.sku})` : ''}
                    </option>
                  ))}
                </select>
              )}
            </div>
          )}

          {newRule.rule_type === 'CATEGORY' && (
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                Category <span className="text-red-500">*</span>
                {isLoadingCategories && <span className="ml-2 text-xs text-gray-500">(Loading...)</span>}
              </label>
              {isLoadingCategories ? (
                <div className="w-full px-3 py-2 border border-gray-300 rounded-lg bg-gray-50 text-gray-500">
                  Loading categories...
                </div>
              ) : categoriesError ? (
                <div className="w-full px-3 py-2 border border-red-300 rounded-lg bg-red-50 text-red-600">
                  Error loading categories: {categoriesError.message || 'Unknown error'}
                </div>
              ) : categories.length === 0 ? (
                <div className="w-full px-3 py-2 border border-yellow-300 rounded-lg bg-yellow-50 text-yellow-600">
                  No categories found. You can still create a rule without a category.
                </div>
              ) : (
                <select
                  value={newRule.category_id}
                  onChange={(e) => setNewRule({ ...newRule, category_id: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                  required
                >
                  <option value="">-- Select Category ({categories.length} available) --</option>
                  {categories.map((category) => (
                    <option key={category.id} value={category.id}>
                      {category.name}
                    </option>
                  ))}
                </select>
              )}
            </div>
          )}

          <div>
            <Input
              label="Minimum Quantity (Optional)"
              type="number"
              min="1"
              value={newRule.min_quantity}
              onChange={(e) => setNewRule({ ...newRule, min_quantity: e.target.value })}
              placeholder="1"
            />
            <p className="mt-1 text-xs text-gray-500">
              Minimum quantity required for this discount to apply (default: 1)
            </p>
          </div>

          <div className="flex justify-end gap-4 pt-4 border-t">
            <Button
              variant="outline"
              onClick={() => {
                setShowAddRuleModal(false);
                setNewRule({ rule_type: 'ALL', product_id: '', category_id: '', min_quantity: 1 });
              }}
              disabled={createRuleMutation.isLoading}
            >
              Cancel
            </Button>
            <Button
              variant="primary"
              onClick={handleCreateRule}
              disabled={
                createRuleMutation.isLoading ||
                (newRule.rule_type === 'PRODUCT' && !newRule.product_id) ||
                (newRule.rule_type === 'CATEGORY' && !newRule.category_id)
              }
              loading={createRuleMutation.isLoading}
            >
              Add Rule
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  );
}

