import { useState, useMemo } from 'react';
import { useCargoes } from '@/hooks/useCargoes';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Trash2, Edit, Plus, Search, AlertCircle } from 'lucide-react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import axios from 'axios';
import CargoFormDialog from '@/components/cargoes/CargoFormDialog';

interface Cargo {
  id: string;
  cargoReference: string;
  description: string;
  quantity: number;
  weight: number;
  status: 'PENDING' | 'LOADED' | 'IN_TRANSIT' | 'DELIVERED' | 'CANCELLED';
  remarks?: string;
  createdAt: Date;
  updatedAt: Date;
}

const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:3001';

export default function CargoesPageEnhanced() {
  const { data: cargoes = [], isLoading, refetch } = useCargoes();
  const queryClient = useQueryClient();
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [editingCargo, setEditingCargo] = useState<Cargo | null>(null);

  const deleteMutation = useMutation({
    mutationFn: (cargoId: string) =>
      axios.delete(`${API_BASE_URL}/api/cargoes/${cargoId}`),
    onSuccess: () => {
      toast.success('Cargo deleted successfully');
      refetch();
      queryClient.invalidateQueries({ queryKey: ['cargoes'] });
    },
    onError: (error) => {
      const message = axios.isAxiosError(error)
        ? error.response?.data?.message || 'Failed to delete cargo'
        : 'Failed to delete cargo';
      toast.error(message);
    },
  });

  const bulkDeleteMutation = useMutation({
    mutationFn: (ids: string[]) =>
      Promise.all(ids.map(id => axios.delete(`${API_BASE_URL}/api/cargoes/${id}`))),
    onSuccess: () => {
      toast.success('Cargoes deleted successfully');
      setSelectedIds(new Set());
      refetch();
      queryClient.invalidateQueries({ queryKey: ['cargoes'] });
    },
    onError: (error) => {
      const message = axios.isAxiosError(error)
        ? error.response?.data?.message || 'Failed to delete cargoes'
        : 'Failed to delete cargoes';
      toast.error(message);
    },
  });

  const filteredCargoes = useMemo(() => {
    let result = cargoes;
    
    if (searchTerm) {
      const lower = searchTerm.toLowerCase();
      result = result.filter(
        cargo =>
          cargo.cargoReference?.toLowerCase().includes(lower) ||
          cargo.description?.toLowerCase().includes(lower)
      );
    }
    
    if (statusFilter) {
      result = result.filter(cargo => cargo.status === statusFilter);
    }
    
    return result;
  }, [cargoes, searchTerm, statusFilter]);

  const toggleSelect = (cargoId: string) => {
    const newSelected = new Set(selectedIds);
    if (newSelected.has(cargoId)) {
      newSelected.delete(cargoId);
    } else {
      newSelected.add(cargoId);
    }
    setSelectedIds(newSelected);
  };

  const toggleSelectAll = () => {
    if (selectedIds.size === filteredCargoes.length && filteredCargoes.length > 0) {
      setSelectedIds(new Set());
    } else {
      setSelectedIds(new Set(filteredCargoes.map(c => c.id)));
    }
  };

  const handleFormSuccess = () => {
    setIsFormOpen(false);
    setEditingCargo(null);
    refetch();
    queryClient.invalidateQueries({ queryKey: ['cargoes'] });
  };

  const handleEdit = (cargo: Cargo) => {
    setEditingCargo(cargo);
    setIsFormOpen(true);
  };

  const handleDelete = (cargoId: string) => {
    if (window.confirm('Are you sure you want to delete this cargo?')) {
      deleteMutation.mutate(cargoId);
    }
  };

  const handleBulkDelete = () => {
    if (selectedIds.size === 0) {
      toast.error('Please select at least one cargo');
      return;
    }
    if (window.confirm(`Delete ${selectedIds.size} cargo(s)?`)) {
      bulkDeleteMutation.mutate(Array.from(selectedIds));
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'PENDING':
        return 'bg-gray-100 text-gray-800';
      case 'LOADED':
        return 'bg-blue-100 text-blue-800';
      case 'IN_TRANSIT':
        return 'bg-purple-100 text-purple-800';
      case 'DELIVERED':
        return 'bg-green-100 text-green-800';
      case 'CANCELLED':
        return 'bg-red-100 text-red-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  const statuses = ['PENDING', 'LOADED', 'IN_TRANSIT', 'DELIVERED', 'CANCELLED'];

  if (isLoading) {
    return <div className="p-6">Loading cargoes...</div>;
  }

  return (
    <div className="space-y-6 p-6">
      <div className="flex items-center justify-between">
        <h1 className="text-3xl font-bold">Cargoes Management</h1>
        <Button onClick={() => {
          setEditingCargo(null);
          setIsFormOpen(true);
        }}>
          <Plus className="mr-2 h-4 w-4" />
          New Cargo
        </Button>
      </div>

      {/* Filters and Search */}
      <Card>
        <CardContent className="pt-6">
          <div className="space-y-4">
            <div className="flex gap-4 items-end">
              <div className="flex-1">
                <label className="text-sm font-medium mb-1 block">Search</label>
                <div className="relative">
                  <Search className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                  <Input
                    placeholder="Search by reference or description..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-10"
                  />
                </div>
              </div>
              <div className="w-48">
                <label className="text-sm font-medium mb-1 block">Status</label>
                <select
                  value={statusFilter}
                  onChange={(e) => setStatusFilter(e.target.value)}
                  className="flex h-10 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="">All statuses</option>
                  {statuses.map(status => (
                    <option key={status} value={status}>
                      {status}
                    </option>
                  ))}
                </select>
              </div>
            </div>
            
            {selectedIds.size > 0 && (
              <div className="flex items-center gap-2 bg-blue-50 p-3 rounded-md">
                <span className="text-sm text-gray-600">{selectedIds.size} selected</span>
                <Button
                  variant="destructive"
                  size="sm"
                  onClick={handleBulkDelete}
                  disabled={bulkDeleteMutation.isPending}
                >
                  <Trash2 className="mr-2 h-4 w-4" />
                  Delete Selected
                </Button>
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Cargoes Table */}
      <Card>
        <CardHeader>
          <CardTitle>All Cargoes ({filteredCargoes.length})</CardTitle>
        </CardHeader>
        <CardContent>
          {filteredCargoes.length === 0 ? (
            <div className="flex items-center justify-center py-12 text-gray-500">
              <AlertCircle className="mr-2 h-5 w-5" />
              No cargoes found
            </div>
          ) : (
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-10">
                      <input
                        type="checkbox"
                        checked={selectedIds.size === filteredCargoes.length && filteredCargoes.length > 0}
                        onChange={toggleSelectAll}
                        className="rounded"
                      />
                    </TableHead>
                    <TableHead>Cargo Reference</TableHead>
                    <TableHead>Description</TableHead>
                    <TableHead>Quantity</TableHead>
                    <TableHead>Weight (kg)</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Created</TableHead>
                    <TableHead>Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredCargoes.map((cargo) => (
                    <TableRow key={cargo.id}>
                      <TableCell>
                        <input
                          type="checkbox"
                          checked={selectedIds.has(cargo.id)}
                          onChange={() => toggleSelect(cargo.id)}
                          className="rounded"
                        />
                      </TableCell>
                      <TableCell className="font-medium">{cargo.cargoReference}</TableCell>
                      <TableCell className="max-w-xs truncate">{cargo.description}</TableCell>
                      <TableCell>{cargo.quantity}</TableCell>
                      <TableCell>{cargo.weight}</TableCell>
                      <TableCell>
                        <Badge className={getStatusColor(cargo.status)}>
                          {cargo.status}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        {new Date(cargo.createdAt).toLocaleDateString()}
                      </TableCell>
                      <TableCell className="flex gap-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleEdit(cargo)}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="destructive"
                          size="sm"
                          onClick={() => handleDelete(cargo.id)}
                          disabled={deleteMutation.isPending}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Form Dialog */}
      <CargoFormDialog
        open={isFormOpen}
        onOpenChange={setIsFormOpen}
        cargo={editingCargo}
        onSuccess={handleFormSuccess}
      />
    </div>
  );
}
