import React, { useState, useMemo } from 'react';
import { 
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow 
} from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { ArrowUpDown, AlertCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { format } from 'date-fns';

export default function ViolationsTable({ 
  violations, 
  onRowClick 
}) {
  const [sortConfig, setSortConfig] = useState({ key: 'violation_date', direction: 'desc' });

  const statusColors = {
    first: 'bg-yellow-100 text-yellow-800',
    second: 'bg-orange-100 text-orange-800',
    third: 'bg-red-100 text-red-800',
    fined: 'bg-slate-800 text-white',
    resolved: 'bg-green-100 text-green-800',
    escalated: 'bg-purple-100 text-purple-800',
    closed: 'bg-green-100 text-green-800',
    new: 'bg-blue-100 text-blue-800',
    open: 'bg-red-100 text-red-800',
    pending: 'bg-yellow-100 text-yellow-800'
  };

  const severityColors = {
    high: 'bg-red-100 text-red-800',
    medium: 'bg-orange-100 text-orange-800',
    low: 'bg-blue-100 text-blue-800'
  };

  const handleSort = (key) => {
    let direction = 'asc';
    if (sortConfig.key === key && sortConfig.direction === 'asc') {
      direction = 'desc';
    }
    setSortConfig({ key, direction });
  };

  const sortedViolations = useMemo(() => {
    let sortableItems = [...violations];
    if (sortConfig.key !== null) {
      sortableItems.sort((a, b) => {
        let aValue = a[sortConfig.key];
        let bValue = b[sortConfig.key];

        // Resolve nested values for sorting
        if (sortConfig.key === 'property') {
          aValue = a.property_owners?.property_address || a.address || '';
          bValue = b.property_owners?.property_address || b.address || '';
        } else if (sortConfig.key === 'unit') {
          aValue = a.unit_info?.property_address || a.property_owners?.unit_id || '';
          bValue = b.unit_info?.property_address || b.property_owners?.unit_id || '';
        } else if (sortConfig.key === 'assigned') {
          aValue = a.assigned_user?.full_name || '';
          bValue = b.assigned_user?.full_name || '';
        }

        if (aValue < bValue) {
          return sortConfig.direction === 'asc' ? -1 : 1;
        }
        if (aValue > bValue) {
          return sortConfig.direction === 'asc' ? 1 : -1;
        }
        return 0;
      });
    }
    return sortableItems;
  }, [violations, sortConfig]);

  if (!violations || violations.length === 0) {
    return (
      <div className="text-center py-12 bg-white rounded-lg border border-slate-200 shadow-sm">
        <AlertCircle className="w-10 h-10 text-slate-300 mx-auto mb-3" />
        <h3 className="text-lg font-medium text-slate-900">No violations found</h3>
        <p className="text-sm text-slate-500">Adjust your filters or date range.</p>
      </div>
    );
  }

  return (
    <div className="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden">
      <div className="overflow-x-auto">
        <Table>
          <TableHeader className="bg-slate-50 border-b border-slate-200">
            <TableRow>
              <TableHead>
                <Button variant="ghost" onClick={() => handleSort('property')} className="font-semibold text-slate-700 hover:bg-slate-200/50 h-8 px-2 -ml-2">
                  Property <ArrowUpDown className="ml-2 h-4 w-4" />
                </Button>
              </TableHead>
              <TableHead>
                <Button variant="ghost" onClick={() => handleSort('unit')} className="font-semibold text-slate-700 hover:bg-slate-200/50 h-8 px-2 -ml-2">
                  Unit <ArrowUpDown className="ml-2 h-4 w-4" />
                </Button>
              </TableHead>
              <TableHead>
                <Button variant="ghost" onClick={() => handleSort('violation_type')} className="font-semibold text-slate-700 hover:bg-slate-200/50 h-8 px-2 -ml-2">
                  Type <ArrowUpDown className="ml-2 h-4 w-4" />
                </Button>
              </TableHead>
              <TableHead className="font-semibold text-slate-700 hidden md:table-cell">Description</TableHead>
              <TableHead>
                <Button variant="ghost" onClick={() => handleSort('violation_date')} className="font-semibold text-slate-700 hover:bg-slate-200/50 h-8 px-2 -ml-2">
                  Date Reported <ArrowUpDown className="ml-2 h-4 w-4" />
                </Button>
              </TableHead>
              <TableHead>
                <Button variant="ghost" onClick={() => handleSort('status')} className="font-semibold text-slate-700 hover:bg-slate-200/50 h-8 px-2 -ml-2">
                  Status <ArrowUpDown className="ml-2 h-4 w-4" />
                </Button>
              </TableHead>
              <TableHead>
                <Button variant="ghost" onClick={() => handleSort('priority')} className="font-semibold text-slate-700 hover:bg-slate-200/50 h-8 px-2 -ml-2">
                  Severity <ArrowUpDown className="ml-2 h-4 w-4" />
                </Button>
              </TableHead>
              <TableHead className="hidden lg:table-cell">
                <Button variant="ghost" onClick={() => handleSort('assigned')} className="font-semibold text-slate-700 hover:bg-slate-200/50 h-8 px-2 -ml-2">
                  Assigned To <ArrowUpDown className="ml-2 h-4 w-4" />
                </Button>
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody className="divide-y divide-slate-100">
            {sortedViolations.map((v) => (
              <TableRow 
                key={v.id} 
                onClick={() => onRowClick(v)}
                className="hover:bg-slate-50/80 cursor-pointer transition-colors"
              >
                <TableCell className="font-medium text-slate-900 max-w-[200px] truncate">
                  {v.property_owners?.property_address || v.address || 'Unknown'}
                </TableCell>
                <TableCell className="text-slate-600">
                  {v.unit_info?.property_address || v.property_owners?.unit_id || '-'}
                </TableCell>
                <TableCell>
                  <span className="font-medium text-slate-800">{v.violation_type || 'General'}</span>
                </TableCell>
                <TableCell className="text-slate-500 max-w-[250px] truncate hidden md:table-cell">
                  {v.description || v.notes || '-'}
                </TableCell>
                <TableCell className="text-slate-600 whitespace-nowrap">
                  {v.violation_date ? format(new Date(v.violation_date), 'MMM d, yyyy') : format(new Date(v.created_at), 'MMM d, yyyy')}
                </TableCell>
                <TableCell>
                  <Badge variant="outline" className={`capitalize whitespace-nowrap ${statusColors[v.status?.toLowerCase()] || 'bg-slate-100 text-slate-800'}`}>
                    {v.status || 'Open'}
                  </Badge>
                </TableCell>
                <TableCell>
                  {v.priority ? (
                    <Badge variant="outline" className={`capitalize whitespace-nowrap border-transparent ${severityColors[v.priority?.toLowerCase()] || 'bg-slate-100 text-slate-800'}`}>
                      {v.priority}
                    </Badge>
                  ) : (
                    <span className="text-slate-400">-</span>
                  )}
                </TableCell>
                <TableCell className="text-slate-600 hidden lg:table-cell whitespace-nowrap">
                  {v.assigned_user?.full_name || 'Unassigned'}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}