import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { usePageHeader } from '@/contexts/PageHeaderContext';
import { Link, useNavigate } from 'react-router-dom';
import { __ } from '@/lib/i18n';
import { CouponsApi, type Coupon } from '@/lib/api/coupons';
import { showErrorToast, showSuccessToast, getPageLoadErrorMessage } from '@/lib/errorHandling';
import { ErrorCard } from '@/components/ErrorCard';
import { LoadingState } from '@/components/LoadingState';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Card } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { Trash2, RefreshCw, Edit, Tag, Search, SlidersHorizontal, MoreHorizontal } from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useFABConfig } from '@/hooks/useFABConfig';
import { CouponFilterSheet } from './components/CouponFilterSheet';
import { CouponCard } from './components/CouponCard';

export default function CouponsIndex() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [discountType, setDiscountType] = useState('');
  const [selectedIds, setSelectedIds] = useState<number[]>([]);
  const [filterSheetOpen, setFilterSheetOpen] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [deleteTargetId, setDeleteTargetId] = useState<number | null>(null);

  // Configure FAB to navigate to new coupon page
  useFABConfig('coupons');

  // Set page header for contextual link
  const { setPageHeader } = usePageHeader();
  React.useEffect(() => {
    setPageHeader(__('Coupons'));
  }, [setPageHeader]);

  // Count active filters
  const activeFiltersCount = discountType && discountType !== 'all' ? 1 : 0;

  // Fetch coupons
  const { data, isLoading, isError, error, refetch } = useQuery({
    queryKey: ['coupons', page, search, discountType],
    queryFn: () => CouponsApi.list({
      page,
      per_page: 20,
      search,
      discount_type: discountType && discountType !== 'all' ? discountType : undefined
    }),
  });

  // Delete mutation
  const deleteMutation = useMutation({
    mutationFn: (id: number) => CouponsApi.delete(id, false),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['coupons'] });
      showSuccessToast(__('Coupon deleted successfully'));
      setSelectedIds([]);
      setShowDeleteDialog(false);
      setDeleteTargetId(null);
    },
    onError: (error) => {
      showErrorToast(error);
      setShowDeleteDialog(false);
      setDeleteTargetId(null);
    },
  });

  const handleDeleteClick = (id?: number) => {
    if (id) {
      setDeleteTargetId(id);
    } else {
      setDeleteTargetId(null);
    }
    setShowDeleteDialog(true);
  };

  const confirmDelete = () => {
    if (deleteTargetId) {
      deleteMutation.mutate(deleteTargetId);
    } else {
      for (const id of selectedIds) {
        deleteMutation.mutate(id);
      }
    }
  };

  // Toggle selection
  const toggleSelection = (id: number) => {
    setSelectedIds(prev =>
      prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id]
    );
  };

  // Toggle all
  const toggleAll = () => {
    if (selectedIds.length === data?.coupons.length) {
      setSelectedIds([]);
    } else {
      setSelectedIds(data?.coupons.map(c => c.id) || []);
    }
  };

  // Format discount type
  const formatDiscountType = (type: string) => {
    const types: Record<string, string> = {
      'percent': __('Percentage'),
      'fixed_cart': __('Fixed Cart'),
      'fixed_product': __('Fixed Product'),
    };
    return types[type] || type;
  };

  // Format amount
  const formatAmount = (coupon: Coupon) => {
    if (coupon.discount_type === 'percent') {
      return `${coupon.amount}%`;
    }
    return `Rp${coupon.amount.toLocaleString('id-ID')}`;
  };

  if (isLoading) {
    return <LoadingState message={__('Loading coupons...')} />;
  }

  if (isError) {
    return (
      <ErrorCard
        title={__('Failed to load coupons')}
        message={getPageLoadErrorMessage(error)}
        onRetry={() => refetch()}
      />
    );
  }

  const coupons = data?.coupons || [];
  const hasActiveFilters = search || (discountType && discountType !== 'all');

  return (
    <div className="space-y-4 w-full pb-4">
      {/* Mobile: Search + Filter */}
      <div className="md:hidden">
        <div className="flex gap-2 items-center">
          {/* Search Input */}
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder={__('Search coupons...')}
              className="w-full pl-10 pr-4 py-2.5 rounded-lg border border-border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
            />
          </div>

          {/* Filter Button */}
          <button
            onClick={() => setFilterSheetOpen(true)}
            className="relative flex-shrink-0 p-2.5 rounded-lg border border-border bg-background hover:bg-accent transition-colors"
          >
            <SlidersHorizontal className="w-5 h-5" />
            {activeFiltersCount > 0 && (
              <span className="absolute -top-1 -right-1 w-5 h-5 bg-primary text-primary-foreground text-xs font-medium rounded-full flex items-center justify-center">
                {activeFiltersCount}
              </span>
            )}
          </button>
        </div>
      </div>

      {/* Desktop Toolbar */}
      <div className="hidden md:block rounded-lg border border-border p-4 bg-card">
        <div className="flex flex-col lg:flex-row lg:justify-between lg:items-center gap-3">

          {/* Left: Bulk Actions */}
          <div className="flex gap-3">
            {/* Delete - Show only when items selected */}
            {selectedIds.length > 0 && (
              <Button
                variant="destructive"
                size="sm"
                onClick={() => handleDeleteClick()}
                disabled={deleteMutation.isPending}
              >
                <Trash2 className="w-4 h-4 mr-2" />
                {__('Delete')} ({selectedIds.length})
              </Button>
            )}

            {/* Refresh - Always visible (REQUIRED per SOP) */}
            <button
              className="border rounded-md px-3 py-2 text-sm hover:bg-accent disabled:opacity-50 inline-flex items-center gap-2"
              onClick={() => refetch()}
              disabled={isLoading}
            >
              <RefreshCw className="w-4 h-4" />
              {__('Refresh')}
            </button>

            {/* New Coupon - Desktop only */}
            <button
              className="border rounded-md px-3 py-2 text-sm bg-primary text-primary-foreground hover:bg-primary/90 inline-flex items-center gap-2"
              onClick={() => navigate('/coupons/new')}
            >
              <Tag className="w-4 h-4" />
              {__('New Coupon')}
            </button>
          </div>

          {/* Right: Filters */}
          <div className="flex gap-3 flex-wrap items-center">
            {/* Discount Type Filter */}
            <Select value={discountType || undefined} onValueChange={(value) => setDiscountType(value || '')}>
              <SelectTrigger className="w-[180px]">
                <SelectValue placeholder={__('All types')} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">{__('All types')}</SelectItem>
                <SelectItem value="percent">{__('Percentage')}</SelectItem>
                <SelectItem value="fixed_cart">{__('Fixed Cart')}</SelectItem>
                <SelectItem value="fixed_product">{__('Fixed Product')}</SelectItem>
              </SelectContent>
            </Select>

            {/* Search */}
            <Input
              placeholder={__('Search coupons...')}
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-[200px]"
            />

            {/* Reset Filters - Text link style per SOP */}
            {hasActiveFilters && (
              <button
                className="text-sm text-muted-foreground hover:text-foreground underline"
                onClick={() => {
                  setSearch('');
                  setDiscountType('');
                }}
              >
                {__('Clear filters')}
              </button>
            )}
          </div>
        </div>
      </div>

      {/* Desktop Table */}
      <div className="hidden md:block rounded-lg border overflow-hidden">
        <table className="w-full">
          <thead className="bg-muted/50">
            <tr className="border-b">
              <th className="w-12 p-3">
                <Checkbox
                  checked={selectedIds.length === coupons.length && coupons.length > 0}
                  onCheckedChange={toggleAll}
                />
              </th>
              <th className="text-left p-3 font-medium">{__('Code')}</th>
              <th className="text-left p-3 font-medium">{__('Type')}</th>
              <th className="text-left p-3 font-medium">{__('Amount')}</th>
              <th className="text-left p-3 font-medium">{__('Usage')}</th>
              <th className="text-left p-3 font-medium">{__('Expires')}</th>
              <th className="text-center p-3 font-medium">{__('Actions')}</th>
            </tr>
          </thead>
          <tbody>
            {coupons.length === 0 ? (
              <tr>
                <td colSpan={7} className="p-8 text-center text-muted-foreground">
                  <Tag className="w-12 h-12 mx-auto mb-2 opacity-50" />
                  {hasActiveFilters ? __('No coupons found matching your filters') : __('No coupons yet')}
                  {!hasActiveFilters && (
                    <p className="text-sm mt-1">{__('Create your first coupon to get started')}</p>
                  )}
                </td>
              </tr>
            ) : (
              coupons.map((coupon) => (
                <tr key={coupon.id} className="border-b hover:bg-muted/30 last:border-0">
                  <td className="p-3">
                    <Checkbox
                      checked={selectedIds.includes(coupon.id)}
                      onCheckedChange={() => toggleSelection(coupon.id)}
                    />
                  </td>
                  <td className="p-3">
                    <Link to={`/coupons/${coupon.id}/edit`} className="font-medium hover:underline">
                      {coupon.code}
                    </Link>
                    {coupon.description && (
                      <div className="text-sm text-muted-foreground line-clamp-1">
                        {coupon.description}
                      </div>
                    )}
                  </td>
                  <td className="p-3">
                    <Badge variant="outline">{formatDiscountType(coupon.discount_type)}</Badge>
                  </td>
                  <td className="p-3 font-medium">{formatAmount(coupon)}</td>
                  <td className="p-3">
                    <div className="text-sm">
                      {coupon.usage_count} / {coupon.usage_limit || '∞'}
                    </div>
                  </td>
                  <td className="p-3">
                    {coupon.date_expires ? (
                      <div className="text-sm">{new Date(coupon.date_expires).toLocaleDateString('id-ID')}</div>
                    ) : (
                      <div className="text-sm text-muted-foreground">{__('No expiry')}</div>
                    )}
                  </td>
                  <td className="p-3 text-center">
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button variant="ghost" className="h-8 w-8 p-0">
                          <span className="sr-only">{__('Open menu')}</span>
                          <MoreHorizontal className="h-4 w-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuItem onClick={() => navigate(`/coupons/${coupon.id}/edit`)}>
                          <Edit className="mr-2 h-4 w-4" />
                          {__('Edit')}
                        </DropdownMenuItem>
                        <DropdownMenuSeparator />
                        <DropdownMenuItem
                          className="text-destructive focus:text-destructive"
                          onClick={() => handleDeleteClick(coupon.id)}
                        >
                          <Trash2 className="mr-2 h-4 w-4" />
                          {__('Delete')}
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* Mobile Cards */}
      <div className="md:hidden space-y-3">
        {coupons.length === 0 ? (
          <Card className="p-8 text-center text-muted-foreground">
            <Tag className="w-12 h-12 mx-auto mb-2 opacity-50" />
            {hasActiveFilters ? __('No coupons found matching your filters') : __('No coupons yet')}
            {!hasActiveFilters && (
              <p className="text-sm mt-1">{__('Create your first coupon to get started')}</p>
            )}
          </Card>
        ) : (
          coupons.map((coupon) => (
            <CouponCard
              key={coupon.id}
              coupon={coupon}
              selected={selectedIds.includes(coupon.id)}
              onSelect={toggleSelection}
            />
          ))
        )}
      </div>

      {/* Pagination */}
      {data && data.total_pages > 1 && (
        <div className="flex items-center justify-between">
          <div className="text-sm text-muted-foreground">
            {__('Page')} {page} {__('of')} {data.total_pages}
          </div>
          <div className="flex gap-2">
            <button
              className="border rounded-md px-3 py-2 text-sm hover:bg-accent disabled:opacity-50"
              onClick={() => setPage(p => Math.max(1, p - 1))}
              disabled={page === 1}
            >
              {__('Previous')}
            </button>
            <button
              className="border rounded-md px-3 py-2 text-sm hover:bg-accent disabled:opacity-50"
              onClick={() => setPage(p => p + 1)}
              disabled={page >= data.total_pages}
            >
              {__('Next')}
            </button>
          </div>
        </div>
      )}

      {/* Mobile Filter Sheet */}
      <CouponFilterSheet
        open={filterSheetOpen}
        onClose={() => setFilterSheetOpen(false)}
        filters={{ discount_type: discountType }}
        onFiltersChange={(filters) => setDiscountType(filters.discount_type)}
        onReset={() => setDiscountType('')}
      />
    </div>
  );
}
