import { useState, useEffect } from 'react';
import { Card, CardContent } from './ui/card';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Skeleton } from './ui/skeleton';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from './ui/table';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from './ui/dialog';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from './ui/tooltip';
import { Search, CheckCircle2, XCircle, AlertCircle, Activity as ActivityIcon } from 'lucide-react';
import { activityService } from '../services/activity';
import { workflowService } from '../services/workflows';
import { ActivityLog } from '../types/activity';
import { cn, formatRelativeTime } from '../lib/utils';

export default function Activity() {
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [logs, setLogs] = useState<ActivityLog[]>([]);
  const [workflows, setWorkflows] = useState<Record<number, string>>({});
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedLog, setSelectedLog] = useState<ActivityLog | null>(null);

  const fetchLogs = async () => {
    setLoading(true);
    setError(null);
    try {
      const [logsData, workflowsData] = await Promise.all([
        activityService.getActivityLogs({ limit: 50 }),
        workflowService.getWorkflows(),
      ]);
      setLogs(logsData);
      const workflowMap = workflowsData.reduce(
        (acc, workflow) => {
          acc[workflow.id] = workflow.name;
          return acc;
        },
        {} as Record<number, string>,
      );
      setWorkflows(workflowMap);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to load activity logs';
      setError(errorMessage);
      console.error('Error fetching activity logs:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchLogs();
  }, []);

  const filteredLogs = logs.filter((log) => {
    const matchesSearch = log.message.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesStatus = statusFilter === 'all' || log.level === statusFilter;
    return matchesSearch && matchesStatus;
  });

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="seq-page-title">Activity Logs</h1>
        <p className="seq-body mt-1">
          View and monitor workflow execution history (30-day retention)
        </p>
      </div>

      {/* Error Message */}
      {error && (
        <div className="bg-error-muted border border-error rounded-lg p-4 flex items-start gap-3">
          <AlertCircle className="h-5 w-5 text-error flex-shrink-0 mt-0.5" />
          <div className="flex-1">
            <h3 className="font-semibold text-sm text-slate-900 mb-1">
              Error Loading Activity Logs
            </h3>
            <p className="text-sm text-slate-500 mb-2">{error}</p>
            <Button size="sm" variant="outline" onClick={fetchLogs}>
              Retry
            </Button>
          </div>
        </div>
      )}

      {/* Search and Filters */}
      <Card>
        <CardContent className="p-4">
          <div className="flex flex-col sm:flex-row gap-4">
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
              <Input
                placeholder="Search logs..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10"
              />
            </div>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-full sm:w-48">
                <SelectValue placeholder="Level" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Levels</SelectItem>
                <SelectItem value="info">Info</SelectItem>
                <SelectItem value="warning">Warning</SelectItem>
                <SelectItem value="error">Error</SelectItem>
                <SelectItem value="critical">Critical</SelectItem>
              </SelectContent>
            </Select>
            <Button variant="outline" className="flex items-center gap-2" onClick={fetchLogs}>
              Refresh
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* Loading State - Skeleton */}
      {loading && (
        <Card>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Level</TableHead>
                <TableHead>Workflow</TableHead>
                <TableHead>Message</TableHead>
                <TableHead>Timestamp</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {[1, 2, 3, 4].map((i) => (
                <TableRow key={i}>
                  <TableCell>
                    <Skeleton className="h-5 w-16 skeleton-shimmer" />
                  </TableCell>
                  <TableCell>
                    <Skeleton className="h-4 w-8 skeleton-shimmer" />
                  </TableCell>
                  <TableCell>
                    <Skeleton className="h-4 w-48 skeleton-shimmer" />
                  </TableCell>
                  <TableCell>
                    <Skeleton className="h-4 w-32 skeleton-shimmer" />
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Card>
      )}

      {/* Empty State */}
      {!loading && !error && logs.length === 0 && (
        <Card className="animate-fade-in">
          <CardContent className="p-12 flex flex-col items-center text-center">
            <div className="w-16 h-16 rounded-full bg-slate-100 flex items-center justify-center mb-4">
              <ActivityIcon className="h-8 w-8 text-slate-400" />
            </div>
            <h3 className="text-lg font-semibold text-slate-900 mb-2">No activity yet</h3>
            <p className="text-sm text-slate-500 max-w-sm">
              Activity logs will appear here once your workflows start executing. Create and
              activate a workflow to get started.
            </p>
          </CardContent>
        </Card>
      )}

      {/* Activity Table */}
      {!loading && !error && logs.length > 0 && (
        <Card>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Level</TableHead>
                  <TableHead>Workflow</TableHead>
                  <TableHead>Message</TableHead>
                  <TableHead>Timestamp</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredLogs.map((log) => (
                  <TableRow
                    key={log.id}
                    className={cn(
                      'transition-colors',
                      log.level === 'error' && 'bg-red-50/50 hover:bg-red-50',
                      log.level === 'critical' && 'bg-red-100/50 hover:bg-red-100',
                      log.level === 'warning' && 'bg-yellow-50/50 hover:bg-yellow-50',
                      log.level === 'info' && 'hover:bg-slate-50',
                    )}
                  >
                    <TableCell>
                      {log.level === 'info' && (
                        <div className="flex items-center gap-2 text-success">
                          <CheckCircle2 className="h-4 w-4" />
                          <span className="text-sm font-medium">Info</span>
                        </div>
                      )}
                      {log.level === 'warning' && (
                        <div className="flex items-center gap-2 text-warning">
                          <AlertCircle className="h-4 w-4" />
                          <span className="text-sm font-medium">Warning</span>
                        </div>
                      )}
                      {(log.level === 'error' || log.level === 'critical') && (
                        <div className="flex items-center gap-2 text-error">
                          <XCircle className="h-4 w-4" />
                          <span className="text-sm font-medium">
                            {log.level === 'critical' ? 'Critical' : 'Error'}
                          </span>
                        </div>
                      )}
                    </TableCell>
                    <TableCell className="text-sm text-slate-500">
                      {workflows[log.workflow_id] || `Workflow #${log.workflow_id}`}
                    </TableCell>
                    <TableCell>
                      <div className="text-sm font-medium text-slate-900">{log.message}</div>
                      {log.context && Object.keys(log.context).length > 0 && (
                        <button
                          onClick={() => setSelectedLog(log)}
                          className="text-xs text-cyan-600 mt-1 hover:underline cursor-pointer"
                        >
                          View details
                        </button>
                      )}
                    </TableCell>
                    <TableCell className="text-sm text-slate-500">
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <span className="cursor-default">
                              {formatRelativeTime(log.created_at)}
                            </span>
                          </TooltipTrigger>
                          <TooltipContent>
                            {new Date(log.created_at).toLocaleString()}
                          </TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* Log Details Dialog */}
      <Dialog open={selectedLog !== null} onOpenChange={(open) => !open && setSelectedLog(null)}>
        <DialogContent className="max-w-2xl max-h-[80vh] overflow-auto">
          <DialogHeader>
            <DialogTitle>Log Details</DialogTitle>
            <DialogDescription>
              {selectedLog?.message} -{' '}
              {selectedLog && new Date(selectedLog.created_at).toLocaleString()}
            </DialogDescription>
          </DialogHeader>
          <div className="mt-4">
            <pre className="bg-slate-50 p-4 rounded-lg text-xs overflow-auto max-h-[60vh] font-mono">
              {selectedLog && JSON.stringify(selectedLog.context, null, 2)}
            </pre>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
