'use client';

import { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Ticket, AlertCircle, Filter } from 'lucide-react';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { format } from 'date-fns';

interface RelatedTicketsModalProps {
  configItemId: number;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function RelatedTicketsModal({
  configItemId,
  open,
  onOpenChange,
}: RelatedTicketsModalProps) {
  const [tickets, setTickets] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [hideRmmAlerts, setHideRmmAlerts] = useState(true);

  useEffect(() => {
    if (open && configItemId) {
      fetchRelatedTickets();
    }
  }, [open, configItemId]);

  const fetchRelatedTickets = async () => {
    setLoading(true);
    setError(null);

    try {
      const response = await fetch(`/api/config-items/${configItemId}/tickets`);
      if (!response.ok) {
        throw new Error('Failed to fetch related tickets');
      }

      const result = await response.json();
      setTickets(result.tickets || []);
    } catch (err) {
      console.error('Error fetching related tickets:', err);
      setError(err instanceof Error ? err.message : 'An error occurred');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="!max-w-[95vw] !w-[95vw] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <div className="flex items-start justify-between">
            <div>
              <DialogTitle className="flex items-center gap-2">
                <Ticket className="w-5 h-5" />
                Related Tickets
              </DialogTitle>
              <DialogDescription>
                Tickets associated with this configuration item
              </DialogDescription>
            </div>
            {!loading && !error && tickets.length > 0 && (
              <div className="flex gap-3 mr-8">
                <div className="px-3 py-2 bg-gradient-to-br from-blue-50 to-blue-100 dark:from-blue-950 dark:to-blue-900 rounded-lg">
                  <p className="text-xs text-muted-foreground">Total Tickets</p>
                  <p className="text-sm font-bold">{tickets.length}</p>
                </div>
                <div className="px-3 py-2 bg-gradient-to-br from-green-50 to-green-100 dark:from-green-950 dark:to-green-900 rounded-lg">
                  <p className="text-xs text-muted-foreground">Open</p>
                  <p className="text-sm font-bold">
                    {tickets.filter((t: any) => t.status !== 'Complete' && t.status !== 'Closed').length}
                  </p>
                </div>
              </div>
            )}
          </div>
        </DialogHeader>

        {loading && (
          <div className="space-y-4 py-4">
            <Skeleton className="h-64 w-full" />
          </div>
        )}

        {error && (
          <div className="flex items-center gap-2 text-red-500 p-4 bg-red-50 dark:bg-red-950/20 rounded-lg">
            <AlertCircle className="w-5 h-5" />
            <p>Error: {error}</p>
          </div>
        )}

        {!loading && !error && (
          <div className="py-4">
            {/* Filter Toggle */}
            <div className="flex items-center gap-2 mb-4 p-3 bg-muted/50 rounded-lg">
              <Filter className="w-4 h-4 text-muted-foreground" />
              <Label htmlFor="hide-rmm-alerts" className="text-sm cursor-pointer flex-1">
                Hide RMM Alert Tickets
              </Label>
              <Switch
                id="hide-rmm-alerts"
                checked={hideRmmAlerts}
                onCheckedChange={setHideRmmAlerts}
              />
            </div>
            
            {tickets.filter((ticket: any) => !hideRmmAlerts || ticket.source !== 'RMM Alert').length > 0 ? (
              <div className="border rounded-lg overflow-hidden shadow-sm">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-muted/50">
                      <TableHead className="w-28">Ticket #</TableHead>
                      <TableHead className="min-w-[300px]">Title</TableHead>
                      <TableHead className="w-32">Status</TableHead>
                      <TableHead className="w-32">Priority</TableHead>
                      <TableHead className="w-40">Assigned To</TableHead>
                      <TableHead className="w-32">Created</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {tickets
                      .filter((ticket: any) => !hideRmmAlerts || ticket.source !== 'RMM Alert')
                      .map((ticket: any) => (
                      <TableRow key={ticket.id} className="hover:bg-muted/50 transition-colors">
                        <TableCell className="font-mono font-semibold text-blue-600 dark:text-blue-400">
                          {ticket.ticketNumber}
                        </TableCell>
                        <TableCell className="min-w-[300px]">
                          <div className="text-sm font-medium whitespace-normal break-words">
                            {ticket.title || '-'}
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge 
                            variant={ticket.status === 'Complete' || ticket.status === 'Closed' ? 'secondary' : 'default'}
                          >
                            {ticket.status || '-'}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <Badge 
                            variant={ticket.priority === 'High' || ticket.priority === 'Critical' ? 'destructive' : 'secondary'}
                          >
                            {ticket.priority || '-'}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-sm">{ticket.assignedResourceName || '-'}</TableCell>
                        <TableCell className="whitespace-nowrap text-sm text-muted-foreground">
                          {ticket.createDate ? format(new Date(ticket.createDate), 'MMM d, yyyy') : '-'}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            ) : (
              <div className="text-center py-12 text-muted-foreground">
                <AlertCircle className="w-12 h-12 mx-auto mb-4 opacity-50" />
                <p className="font-medium">
                  {hideRmmAlerts && tickets.length > 0 
                    ? 'All tickets are RMM Alerts (filtered out)'
                    : 'No related tickets found'
                  }
                </p>
                <p className="text-sm mt-2">
                  {hideRmmAlerts && tickets.length > 0
                    ? 'Toggle the filter above to show RMM Alert tickets'
                    : 'This configuration item has no associated tickets'
                  }
                </p>
              </div>
            )}
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}
