import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Link, useNavigate } from 'react-router-dom';
import { __ } from '@/lib/i18n';
import { CustomersApi, type Customer } from '@/lib/api/customers';
import { showErrorToast, showSuccessToast, getPageLoadErrorMessage } from '@/lib/errorHandling';
import { useFABConfig } from '@/hooks/useFABConfig';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { FilterBottomSheet } from '@/components/filters/FilterBottomSheet';
import { Pagination } from '@/components/Pagination';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { ErrorCard } from '@/components/ErrorCard';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Skeleton } from '@/components/ui/skeleton';
import { RefreshCw, Trash2, Search, User, ChevronRight, Edit, MoreHorizontal, Eye } from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { formatMoney } from '@/lib/currency';

export default function CustomersIndex() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();

  // State
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [selectedIds, setSelectedIds] = useState<number[]>([]);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [deleteTargetId, setDeleteTargetId] = useState<number | null>(null);
  const perPage = 20;

  // FAB config - 'none' because submenu has 'New' tab (per SOP)
  useFABConfig('none');

  // Fetch customers
  const customersQuery = useQuery({
    queryKey: ['customers', page, search],
    queryFn: () => CustomersApi.list({ page, per_page: perPage, search }),
  });

  // Delete mutation
  const deleteMutation = useMutation({
    mutationFn: async (ids: number[]) => {
      await Promise.all(ids.map(id => CustomersApi.delete(id)));
    },
    onSuccess: () => {
      showSuccessToast(__('Customers deleted successfully'));
      setSelectedIds([]);
      queryClient.invalidateQueries({ queryKey: ['customers'] });
    },
    onError: (error: any) => {
      showErrorToast(error);
      setShowDeleteDialog(false);
      setDeleteTargetId(null);
    },
  });

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

  const toggleAll = () => {
    if (selectedIds.length === customers.length) {
      setSelectedIds([]);
    } else {
      setSelectedIds(customers.map(c => c.id));
    }
  };

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

  const confirmDelete = () => {
    if (deleteTargetId) {
      deleteMutation.mutate([deleteTargetId]);
    } else if (selectedIds.length > 0) {
      deleteMutation.mutate(selectedIds);
    }
  };

  const handleRefresh = () => {
    queryClient.invalidateQueries({ queryKey: ['customers'] });
  };

  // Data
  const customers = customersQuery.data?.data || [];
  const pagination = customersQuery.data?.pagination;

  // Loading state
  if (customersQuery.isLoading) {
    return (
      <div className="space-y-4">
        <Skeleton className="h-12 w-full" />
        <Skeleton className="h-64 w-full" />
      </div>
    );
  }

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

  return (
    <div className="space-y-4">
      {/* Mobile: Search */}
      <div className="md:hidden">
        <div className="relative">
          <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);
              setPage(1);
            }}
            placeholder={__('Search customers...')}
            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>
      </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">
            {selectedIds.length > 0 && (
              <Button
                variant="destructive"
                size="sm"
                onClick={() => handleDeleteClick()}
                disabled={deleteMutation.isPending}
              >
                <Trash2 className="w-4 h-4 mr-2" />
                {__('Delete Selected')}
              </Button>
            )}

            <button
              onClick={handleRefresh}
              disabled={customersQuery.isFetching}
              className="border rounded-md px-3 py-2 text-sm hover:bg-accent disabled:opacity-50 inline-flex items-center gap-2"
            >
              <RefreshCw className={`w-4 h-4 ${customersQuery.isFetching ? 'animate-spin' : ''}`} />
              {__('Refresh')}
            </button>
          </div>

          {/* Right: Search */}
          <div className="flex gap-3 items-center">
            <div className="relative">
              <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);
                  setPage(1);
                }}
                placeholder={__('Search customers...')}
                className="pl-10 pr-4 py-2 rounded-lg border border-border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent w-64"
              />
            </div>
          </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 === customers.length && customers.length > 0}
                  onCheckedChange={toggleAll}
                  aria-label={__('Select all')}
                />
              </th>
              <th className="text-left p-3 font-medium">{__('Customer')}</th>
              <th className="text-left p-3 font-medium">{__('Email')}</th>
              <th className="text-left p-3 font-medium">{__('Type')}</th>
              <th className="text-left p-3 font-medium">{__('Orders')}</th>
              <th className="text-left p-3 font-medium">{__('Total Spent')}</th>
              <th className="text-left p-3 font-medium">{__('Registered')}</th>
              <th className="text-left p-3 font-medium">{__('Actions')}</th>
            </tr>
          </thead>
          <tbody>
            {customers.length === 0 ? (
              <tr>
                <td colSpan={8} className="p-8 text-center text-muted-foreground">
                  <User className="w-12 h-12 mx-auto mb-2 opacity-50" />
                  {search ? __('No customers found matching your search') : __('No customers yet')}
                  {!search && (
                    <p className="text-sm mt-1">
                      <Link to="/customers/new" className="text-primary hover:underline">
                        {__('Create your first customer')}
                      </Link>
                    </p>
                  )}
                </td>
              </tr>
            ) : (
              customers.map((customer) => (
                <tr key={customer.id} className="border-b hover:bg-muted/30 last:border-0">
                  <td className="p-3">
                    <Checkbox
                      checked={selectedIds.includes(customer.id)}
                      onCheckedChange={() => toggleSelection(customer.id)}
                      aria-label={__('Select customer')}
                    />
                  </td>
                  <td className="p-3">
                    <Link to={`/customers/${customer.id}`} className="font-medium hover:underline">
                      {customer.display_name || `${customer.first_name} ${customer.last_name}`}
                    </Link>
                  </td>
                  <td className="p-3 text-sm text-muted-foreground">{customer.email}</td>
                  <td className="p-3">
                    <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${customer.role === 'customer' ? 'bg-blue-100 text-blue-800' : 'bg-gray-100 text-gray-800'
                      }`}>
                      {customer.role === 'customer' ? __('Member') : __('Guest')}
                    </span>
                  </td>
                  <td className="p-3 text-sm">{customer.stats?.total_orders || 0}</td>
                  <td className="p-3 text-sm font-medium">
                    {customer.stats?.total_spent ? formatMoney(customer.stats.total_spent) : '—'}
                  </td>
                  <td className="p-3 text-sm text-muted-foreground">
                    {new Date(customer.registered).toLocaleDateString()}
                  </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(`/customers/${customer.id}`)}>
                          <Eye className="mr-2 h-4 w-4" />
                          {__('View Details')}
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => navigate(`/customers/${customer.id}/edit`)}>
                          <Edit className="mr-2 h-4 w-4" />
                          {__('Edit')}
                        </DropdownMenuItem>
                        <DropdownMenuSeparator />
                        <DropdownMenuItem
                          className="text-destructive focus:text-destructive"
                          onClick={() => handleDeleteClick(customer.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">
        {customers.length === 0 ? (
          <Card className="p-8 text-center text-muted-foreground">
            <User className="w-12 h-12 mx-auto mb-2 opacity-50" />
            {search ? __('No customers found') : __('No customers yet')}
          </Card>
        ) : (
          customers.map((customer) => (
            <Link
              key={customer.id}
              to={`/customers/${customer.id}`}
              className="block bg-card border border-border rounded-xl p-3 hover:bg-accent/50 transition-colors active:scale-[0.98] active:transition-transform shadow-sm"
            >
              <div className="flex items-center gap-3">
                {/* Checkbox */}
                <div
                  onClick={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    toggleSelection(customer.id);
                  }}
                >
                  <Checkbox
                    checked={selectedIds.includes(customer.id)}
                    aria-label={__('Select customer')}
                    className="w-5 h-5"
                  />
                </div>

                {/* Content */}
                <div className="flex-1 min-w-0">
                  {/* Line 1: Name */}
                  <h3 className="font-bold text-base leading-tight mb-1">
                    {customer.display_name || `${customer.first_name} ${customer.last_name}`}
                  </h3>

                  {/* Line 2: Email */}
                  <div className="text-sm text-muted-foreground truncate mb-2">
                    {customer.email}
                  </div>

                  {/* Line 3: Stats */}
                  <div className="flex items-center gap-3 text-xs text-muted-foreground mb-1">
                    <span>{customer.stats?.total_orders || 0} {__('orders')}</span>
                    <span>{new Date(customer.registered).toLocaleDateString()}</span>
                  </div>

                  {/* Line 4: Total Spent */}
                  <div className="font-bold text-lg tabular-nums text-primary">
                    {customer.stats?.total_spent ? formatMoney(customer.stats.total_spent) : '—'}
                  </div>
                </div>

                {/* Chevron */}
                <ChevronRight className="w-5 h-5 text-muted-foreground flex-shrink-0" />
              </div>
            </Link>
          ))
        )}
      </div>

      {/* Pagination */}
      {!customersQuery.isLoading && !customersQuery.isError && pagination && (
        <Pagination
          page={page}
          perPage={perPage}
          total={pagination.total_items}
          onPageChange={setPage}
        />
      )}

      {/* Delete Confirmation Dialog */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{__('Delete Customers')}</AlertDialogTitle>
            <AlertDialogDescription>
              {deleteTargetId
                ? __('Are you sure you want to delete this customer?')
                : __('Are you sure you want to delete ') + selectedIds.length + __(' customers?')}
              <br />
              <span className="text-red-600 font-medium">{__('This action cannot be undone.')}</span>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel
              onClick={() => {
                setShowDeleteDialog(false);
                setDeleteTargetId(null);
              }}
              disabled={deleteMutation.isPending}
            >
              {__('Cancel')}
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmDelete}
              disabled={deleteMutation.isPending}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {deleteMutation.isPending ? __('Deleting...') : __('Delete')}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
