'use client';

import { useRef, useEffect, useState } from 'react';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import {
  Trash2,
  Search,
  AlertTriangle,
  AlertCircle,
  Info,
  MessageSquare,
  Filter,
  ChevronDown,
} from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuCheckboxItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';

import { usePreviewStore } from '@/stores/preview-store';
import { ConsoleOutput } from '@/lib/preview/types';

// Icons for different output types
const OUTPUT_ICONS: Record<ConsoleOutput['type'], React.ReactNode> = {
  log: <MessageSquare className="h-3 w-3" />,
  warn: <AlertTriangle className="h-3 w-3" />,
  error: <AlertCircle className="h-3 w-3" />,
  info: <Info className="h-3 w-3" />,
};

// Colors for different output types
const OUTPUT_COLORS: Record<ConsoleOutput['type'], string> = {
  log: 'text-foreground',
  warn: 'text-yellow-500',
  error: 'text-red-500',
  info: 'text-blue-500',
};

const OUTPUT_BG: Record<ConsoleOutput['type'], string> = {
  log: 'bg-transparent',
  warn: 'bg-yellow-500/5',
  error: 'bg-red-500/5',
  info: 'bg-blue-500/5',
};

interface PreviewConsoleProps {
  className?: string;
}

export default function PreviewConsole({ className }: PreviewConsoleProps) {
  const { consoleOutputs, clearConsole } = usePreviewStore();
  const scrollRef = useRef<HTMLDivElement>(null);
  const [autoScroll, setAutoScroll] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [filters, setFilters] = useState({
    log: true,
    warn: true,
    error: true,
    info: true,
  });

  // Auto-scroll to bottom when new output arrives
  useEffect(() => {
    if (autoScroll && scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [consoleOutputs, autoScroll]);

  // Filter outputs
  const filteredOutputs = consoleOutputs.filter((output) => {
    // Type filter
    if (!filters[output.type]) return false;

    // Search filter
    if (searchQuery) {
      return output.message.toLowerCase().includes(searchQuery.toLowerCase());
    }

    return true;
  });

  // Count by type
  const counts = consoleOutputs.reduce(
    (acc, output) => {
      acc[output.type] = (acc[output.type] || 0) + 1;
      return acc;
    },
    { log: 0, warn: 0, error: 0, info: 0 } as Record<string, number>
  );

  // Format timestamp
  const formatTime = (timestamp: number) => {
    const date = new Date(timestamp);
    return date.toLocaleTimeString('en-US', {
      hour12: false,
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      fractionalSecondDigits: 3,
    });
  };

  return (
    <div className={`flex flex-col h-full bg-card ${className || ''}`}>
      {/* Header */}
      <div className="flex items-center justify-between px-3 py-2 border-b">
        <div className="flex items-center gap-2">
          <span className="font-medium text-sm">Console</span>
          {counts.error > 0 && (
            <Badge variant="destructive" className="h-5 px-1.5 text-xs">
              {counts.error}
            </Badge>
          )}
          {counts.warn > 0 && (
            <Badge
              variant="secondary"
              className="h-5 px-1.5 text-xs bg-yellow-500/20 text-yellow-600"
            >
              {counts.warn}
            </Badge>
          )}
        </div>

        <div className="flex items-center gap-1">
          {/* Search */}
          <div className="relative">
            <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3 w-3 text-muted-foreground" />
            <Input
              placeholder="Filter..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="h-7 w-32 pl-7 text-xs"
            />
          </div>

          {/* Filter dropdown */}
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="ghost" size="icon" className="h-7 w-7">
                <Filter className="h-3 w-3" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuCheckboxItem
                checked={filters.log}
                onCheckedChange={(checked) =>
                  setFilters((f) => ({ ...f, log: checked }))
                }
              >
                <MessageSquare className="h-3 w-3 mr-2" />
                Logs ({counts.log})
              </DropdownMenuCheckboxItem>
              <DropdownMenuCheckboxItem
                checked={filters.info}
                onCheckedChange={(checked) =>
                  setFilters((f) => ({ ...f, info: checked }))
                }
              >
                <Info className="h-3 w-3 mr-2 text-blue-500" />
                Info ({counts.info})
              </DropdownMenuCheckboxItem>
              <DropdownMenuCheckboxItem
                checked={filters.warn}
                onCheckedChange={(checked) =>
                  setFilters((f) => ({ ...f, warn: checked }))
                }
              >
                <AlertTriangle className="h-3 w-3 mr-2 text-yellow-500" />
                Warnings ({counts.warn})
              </DropdownMenuCheckboxItem>
              <DropdownMenuCheckboxItem
                checked={filters.error}
                onCheckedChange={(checked) =>
                  setFilters((f) => ({ ...f, error: checked }))
                }
              >
                <AlertCircle className="h-3 w-3 mr-2 text-red-500" />
                Errors ({counts.error})
              </DropdownMenuCheckboxItem>
            </DropdownMenuContent>
          </DropdownMenu>

          {/* Clear button */}
          <Button
            variant="ghost"
            size="icon"
            className="h-7 w-7"
            onClick={clearConsole}
            title="Clear console"
          >
            <Trash2 className="h-3 w-3" />
          </Button>
        </div>
      </div>

      {/* Output list */}
      <ScrollArea
        ref={scrollRef}
        className="flex-1"
        onScrollCapture={(e) => {
          const target = e.target as HTMLDivElement;
          const isAtBottom =
            target.scrollHeight - target.scrollTop - target.clientHeight < 50;
          setAutoScroll(isAtBottom);
        }}
      >
        <div className="font-mono text-xs">
          {filteredOutputs.length === 0 ? (
            <div className="flex items-center justify-center h-32 text-muted-foreground">
              {consoleOutputs.length === 0
                ? 'No output yet. Run a script to see results.'
                : 'No matching results.'}
            </div>
          ) : (
            filteredOutputs.map((output) => (
              <div
                key={output.id}
                className={`flex items-start gap-2 px-3 py-1 border-b border-border/50 hover:bg-accent/5 ${OUTPUT_BG[output.type]}`}
              >
                <span className={`mt-0.5 ${OUTPUT_COLORS[output.type]}`}>
                  {OUTPUT_ICONS[output.type]}
                </span>
                <span className="text-muted-foreground text-[10px] mt-0.5 shrink-0">
                  {formatTime(output.timestamp)}
                </span>
                <span
                  className={`flex-1 whitespace-pre-wrap break-all ${OUTPUT_COLORS[output.type]}`}
                >
                  {output.message}
                </span>
              </div>
            ))
          )}
        </div>
      </ScrollArea>

      {/* Auto-scroll indicator */}
      {!autoScroll && filteredOutputs.length > 0 && (
        <div className="absolute bottom-2 right-2">
          <Button
            variant="secondary"
            size="sm"
            className="h-7 text-xs shadow-lg"
            onClick={() => {
              setAutoScroll(true);
              if (scrollRef.current) {
                scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
              }
            }}
          >
            <ChevronDown className="h-3 w-3 mr-1" />
            Scroll to bottom
          </Button>
        </div>
      )}
    </div>
  );
}
