import React from 'react';
import { useSelector } from 'react-redux';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { MapPin, Plus, Edit2, Trash2, Globe } from 'lucide-react';
import { RootState } from '@/store';
import { formatDateTime } from '@/components/ui/utils';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';

interface LocationManagementProps {
  onAddLocation: () => void;
  onEditLocation: (location: any) => void;
  onDeleteLocation: (id: string) => void;
  onSearch: (term: string) => void;
  onPageChange: (page: number) => void;
  searchTerm: string;
  states: any[];
  stateFilter: string;
  onStateFilterChange: (value: string) => void;
  statusFilter: string;
  onStatusFilterChange: (value: string) => void;
}

export const LocationManagement: React.FC<LocationManagementProps> = ({ 
  onAddLocation, onEditLocation, onDeleteLocation, onSearch, onPageChange, searchTerm,
  states, stateFilter, onStateFilterChange,
  statusFilter, onStatusFilterChange
}) => {
  const { allAreas, areasPagination, isAreasLoading } = useSelector((state: RootState) => state.master);

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader>
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div>
              <CardTitle>Dealership Locations</CardTitle>
              <CardDescription>Manage {areasPagination.total} geographical locations and their operational status</CardDescription>
            </div>
            <div className="flex items-center gap-3">
              <div className="relative">
                <Globe className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                <input
                  type="text"
                  placeholder="Search locations..."
                  value={searchTerm}
                  onChange={(e) => onSearch(e.target.value)}
                  className="pl-9 pr-4 py-2 bg-slate-50 border border-slate-200 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-red-500 w-64 transition-all"
                />
              </div>

              <Select value={stateFilter} onValueChange={onStateFilterChange}>
                <SelectTrigger className="w-48">
                  <SelectValue placeholder="All States" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All States</SelectItem>
                  {states.map((s) => (
                    <SelectItem key={s.id} value={s.id}>{s.name || s.stateName}</SelectItem>
                  ))}
                </SelectContent>
              </Select>

              <Select value={statusFilter} onValueChange={onStatusFilterChange}>
                <SelectTrigger className="w-44">
                  <SelectValue placeholder="Opportunity Filter" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Opportunities</SelectItem>
                  <SelectItem value="active">Opportunity: Yes</SelectItem>
                  <SelectItem value="inactive">Opportunity: No</SelectItem>
                </SelectContent>
              </Select>

              <Button onClick={onAddLocation} className="bg-re-red hover:bg-re-red-hover whitespace-nowrap">
                <Plus className="w-4 h-4 mr-2" />
                Add Location
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className={`relative ${isAreasLoading ? 'opacity-50 pointer-events-none' : ''}`}>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>State</TableHead>
                  <TableHead>City</TableHead>
                  <TableHead>District</TableHead>
                  <TableHead>Active Period</TableHead>
                  <TableHead>Opportunity</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {allAreas.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={6} className="h-32 text-center text-slate-500 italic">
                      {searchTerm ? 'No locations found matching your search' : 'No locations available'}
                    </TableCell>
                  </TableRow>
                ) : (
                  allAreas.map((district) => (
                    <TableRow key={district.id}>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <MapPin className="w-4 h-4 text-re-red" />
                          <span className="font-medium">{district.stateName || 'N/A'}</span>
                        </div>
                      </TableCell>
                      <TableCell className="font-medium text-slate-900">{district.city || 'N/A'}</TableCell>
                      <TableCell className="text-slate-600 text-sm">{district.name}</TableCell>
                      <TableCell>
                        {district.openFrom && district.openTo ? (
                          <div className="space-y-1">
                            <div className="flex items-center gap-2 text-xs">
                              <span className="text-slate-600">From:</span>
                              <Badge variant="outline" className="text-xs font-medium">
                                {formatDateTime(district.openFrom)}
                              </Badge>
                            </div>
                            <div className="flex items-center gap-2 text-xs">
                              <span className="text-slate-600">To:</span>
                              <Badge variant="outline" className="text-xs font-medium">
                                {formatDateTime(district.openTo)}
                              </Badge>
                            </div>
                          </div>
                        ) : (
                          <span className="text-slate-400 italic text-sm">Not Defined</span>
                        )}
                      </TableCell>
                      <TableCell>
                        <Badge 
                          variant={district.isOpportunity ? 'default' : 'secondary'} 
                          className={district.isOpportunity ? 'bg-green-600 hover:bg-green-700 text-white border-transparent' : ''}
                        >
                          {district.isOpportunity ? 'Yes' : 'No'}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex gap-2 justify-end">
                          <Button variant="outline" size="sm" onClick={() => onEditLocation(district)} className="h-8 w-8 p-0">
                            <Edit2 className="w-4 h-4" />
                          </Button>
                          <Button variant="outline" size="sm" onClick={() => onDeleteLocation(district.id)} className="h-8 w-8 p-0 text-re-red hover:bg-red-50 hover:text-re-red-hover">
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
            {isAreasLoading && (
              <div className="absolute inset-0 flex items-center justify-center bg-white/10 backdrop-blur-[1px]">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-re-red"></div>
              </div>
            )}
          </div>

          {/* Pagination Controls */}
          {areasPagination.totalPages > 1 && (
            <div className="flex items-center justify-between mt-6 pt-4 border-t border-slate-100">
              <div className="text-sm text-slate-500">
                Showing <span className="font-medium text-slate-900">{(areasPagination.page - 1) * areasPagination.limit + 1}</span> to <span className="font-medium text-slate-900">{Math.min(areasPagination.page * areasPagination.limit, areasPagination.total)}</span> of <span className="font-medium text-slate-900">{areasPagination.total}</span> results
              </div>
              <div className="flex items-center gap-2">
                <Button 
                  variant="outline" 
                  size="sm" 
                  onClick={() => onPageChange(areasPagination.page - 1)}
                  disabled={areasPagination.page <= 1 || isAreasLoading}
                  className="h-8"
                >
                  Previous
                </Button>
                <div className="flex items-center gap-1">
                  {Array.from({ length: Math.min(5, areasPagination.totalPages) }, (_, i) => {
                    // Simple pagination window logic
                    let pageNum = areasPagination.page;
                    if (areasPagination.page <= 3) pageNum = i + 1;
                    else if (areasPagination.page >= areasPagination.totalPages - 2) pageNum = areasPagination.totalPages - 4 + i;
                    else pageNum = areasPagination.page - 2 + i;
                    
                    if (pageNum <= 0 || pageNum > areasPagination.totalPages) return null;

                    return (
                      <Button
                        key={pageNum}
                        variant={areasPagination.page === pageNum ? 'default' : 'outline'}
                        size="sm"
                        onClick={() => onPageChange(pageNum)}
                        disabled={isAreasLoading}
                        className="h-8 w-8 p-0"
                      >
                        {pageNum}
                      </Button>
                    );
                  })}
                </div>
                <Button 
                  variant="outline" 
                  size="sm" 
                  onClick={() => onPageChange(areasPagination.page + 1)}
                  disabled={areasPagination.page >= areasPagination.totalPages || isAreasLoading}
                  className="h-8"
                >
                  Next
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

    </div>
  );
};

