import React, { useState, useMemo, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Search, X, ChevronDown, ChevronRight, File } from 'lucide-react';
import { useEditorStore } from '@/core/store';
import { useSecureFileOpen } from '@/hooks/useSecureFileOpen';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { 
  appleTreeExpand, 
  appleListItem, 
  appleSpringGentle,
  appleButtonPress 
} from '@/lib/apple-animations';

interface SearchResult {
  fileId: string;
  fileName: string;
  line: number;
  content: string;
  matchStart: number;
  matchEnd: number;
}

export const SearchPanel: React.FC = () => {
  const { searchQuery, setSearchQuery, files } = useEditorStore();
  const { openFile, UnlockDialog } = useSecureFileOpen();
  const [isExpanded, setIsExpanded] = useState<Record<string, boolean>>({});

  const results = useMemo(() => {
    if (!searchQuery.trim()) return [];

    const searchResults: SearchResult[] = [];
    const query = searchQuery.toLowerCase();

    files
      .filter((f) => f.type === 'file' && f.content)
      .forEach((file) => {
        const lines = file.content!.split('\n');
        lines.forEach((line, index) => {
          const lowerLine = line.toLowerCase();
          let matchStart = lowerLine.indexOf(query);
          while (matchStart !== -1) {
            searchResults.push({
              fileId: file.id,
              fileName: file.name,
              line: index + 1,
              content: line,
              matchStart,
              matchEnd: matchStart + query.length,
            });
            matchStart = lowerLine.indexOf(query, matchStart + 1);
          }
        });
      });

    return searchResults;
  }, [searchQuery, files]);

  const groupedResults = useMemo(() => {
    const groups: Record<string, SearchResult[]> = {};
    results.forEach((result) => {
      if (!groups[result.fileId]) {
        groups[result.fileId] = [];
      }
      groups[result.fileId].push(result);
    });
    return groups;
  }, [results]);

  const toggleExpanded = useCallback((fileId: string) => {
    setIsExpanded((prev) => ({ ...prev, [fileId]: !prev[fileId] }));
  }, []);

  const highlightMatch = (content: string, start: number, end: number) => {
    return (
      <>
        <span className="text-muted-foreground">{content.substring(0, start)}</span>
        <span className="bg-primary/30 text-primary">{content.substring(start, end)}</span>
        <span className="text-muted-foreground">{content.substring(end)}</span>
      </>
    );
  };

  return (
    <div className="h-full flex flex-col">
      <div className="px-3 py-2 border-b border-sidebar-border">
        <div className="relative flex items-center">
          <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3 h-3 text-muted-foreground pointer-events-none" />
          <Input
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Search in files..."
            className="h-7 pl-7 pr-7 text-xs bg-sidebar-accent border-sidebar-border"
          />
          <AnimatePresence>
            {searchQuery && (
              <motion.div
                initial={{ opacity: 0, scale: 0.8 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 0.8 }}
                transition={appleSpringGentle}
                className="absolute right-0 top-0 bottom-0 flex items-center justify-center pr-1"
              >
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-5 w-5 shrink-0"
                  onClick={() => setSearchQuery('')}
                  {...appleButtonPress}
                >
                  <X className="w-3 h-3" />
                </Button>
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </div>

      <ScrollArea className="flex-1">
        <div className="py-1">
          {searchQuery && results.length === 0 ? (
            <div className="px-3 py-8 text-center">
              <Search className="w-8 h-8 mx-auto text-muted-foreground/30 mb-2" />
              <p className="text-xs text-muted-foreground">No results found</p>
            </div>
          ) : (
            Object.entries(groupedResults).map(([fileId, fileResults]) => {
              const expanded = isExpanded[fileId] !== false;
              return (
                <div key={fileId}>
                  <motion.div
                    className="flex items-center gap-2 px-3 py-1 hover:bg-sidebar-accent cursor-pointer"
                    onClick={() => toggleExpanded(fileId)}
                    whileHover={{ x: 2 }}
                    transition={appleSpringGentle}
                  >
                    {expanded ? (
                      <ChevronDown className="w-3 h-3 text-muted-foreground" />
                    ) : (
                      <ChevronRight className="w-3 h-3 text-muted-foreground" />
                    )}
                    <File className="w-3 h-3 text-muted-foreground" />
                    <span className="text-sm flex-1 truncate">{fileResults[0].fileName}</span>
                    <span className="text-xs text-muted-foreground bg-muted px-1.5 rounded">
                      {fileResults.length}
                    </span>
                  </motion.div>
                  <AnimatePresence>
                    {expanded && (
                      <motion.div
                        {...appleTreeExpand}
                        transition={appleSpringGentle}
                      >
                      {fileResults.map((result, index) => (
                        <motion.div
                          key={`${result.fileId}-${result.line}-${index}`}
                          className="pl-8 pr-3 py-0.5 text-xs hover:bg-sidebar-accent cursor-pointer font-mono"
                          onClick={() => openFile(result.fileId)}
                          {...appleListItem}
                          transition={appleSpringGentle}
                          whileHover={{ x: 2 }}
                        >
                          <span className="text-muted-foreground mr-2">{result.line}:</span>
                          <span className="truncate">
                            {highlightMatch(
                              result.content.trim().substring(0, 80),
                              result.matchStart,
                              result.matchEnd
                            )}
                          </span>
                        </motion.div>
                      ))}
                      </motion.div>
                    )}
                  </AnimatePresence>
                </div>
              );
            })
          )}
        </div>
      </ScrollArea>

      {results.length > 0 && (
        <div className="px-3 py-1.5 border-t border-sidebar-border text-xs text-muted-foreground">
          {results.length} result{results.length !== 1 ? 's' : ''} in{' '}
          {Object.keys(groupedResults).length} file{Object.keys(groupedResults).length !== 1 ? 's' : ''}
        </div>
      )}
      {UnlockDialog}
    </div>
  );
};

export default SearchPanel;
