'use client';

import * as React from 'react';
import Fuse from 'fuse.js';
import { Search } from 'lucide-react';
import { cn } from '@/lib/utils/cn';
import { Input } from '@/components/ui/Input';
import { Card } from '@/components/ui/Card';
import type { ConversionFormat } from '@/types/conversion';

export interface FormatSelectorProps {
  formats: ConversionFormat[];
  selectedFormat?: ConversionFormat;
  onFormatSelect: (format: ConversionFormat) => void;
  label?: string;
  disabled?: boolean;
}

export function FormatSelector({
  formats,
  selectedFormat,
  onFormatSelect,
  label = 'Select format',
  disabled = false,
}: FormatSelectorProps) {
  const [searchQuery, setSearchQuery] = React.useState('');
  const [filteredFormats, setFilteredFormats] = React.useState<ConversionFormat[]>(formats);

  // Set up Fuse.js for fuzzy search
  const fuse = React.useMemo(() => {
    return new Fuse(formats, {
      keys: ['name', 'extension', 'description'],
      threshold: 0.3,
      includeScore: true,
    });
  }, [formats]);

  // Filter formats based on search query
  React.useEffect(() => {
    if (!searchQuery.trim()) {
      setFilteredFormats(formats);
      return;
    }

    const results = fuse.search(searchQuery);
    setFilteredFormats(results.map((result) => result.item));
  }, [searchQuery, formats, fuse]);

  // Group formats by category
  const groupedFormats = React.useMemo(() => {
    const groups: Record<string, ConversionFormat[]> = {};

    filteredFormats.forEach((format) => {
      if (!groups[format.category]) {
        groups[format.category] = [];
      }
      groups[format.category].push(format);
    });

    return groups;
  }, [filteredFormats]);

  return (
    <div className="w-full">
      <label className="text-sm font-medium text-foreground mb-2 block">{label}</label>

      {/* Search input */}
      <div className="relative mb-3">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
        <Input
          type="text"
          placeholder="Search formats..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          disabled={disabled}
          className="pl-10"
        />
      </div>

      {/* Format list */}
      <Card className="max-h-64 overflow-y-auto custom-scrollbar">
        {Object.entries(groupedFormats).length === 0 ? (
          <div className="p-4 text-center text-sm text-muted-foreground">
            No formats found matching "{searchQuery}"
          </div>
        ) : (
          <div className="p-2">
            {Object.entries(groupedFormats).map(([category, categoryFormats]) => (
              <div key={category} className="mb-3 last:mb-0">
                <h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-2 px-2">
                  {category}
                </h3>
                <div className="space-y-1">
                  {categoryFormats.map((format) => (
                    <button
                      key={format.id}
                      onClick={() => !disabled && onFormatSelect(format)}
                      disabled={disabled}
                      className={cn(
                        'w-full text-left px-3 py-2 rounded-md transition-colors',
                        'hover:bg-accent hover:text-accent-foreground',
                        'disabled:opacity-50 disabled:cursor-not-allowed',
                        {
                          'bg-primary text-primary-foreground hover:bg-primary/90':
                            selectedFormat?.id === format.id,
                        }
                      )}
                    >
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="text-sm font-medium">{format.name}</p>
                          {format.description && (
                            <p className="text-xs opacity-75 mt-0.5">{format.description}</p>
                          )}
                        </div>
                        <span className="text-xs font-mono opacity-75">.{format.extension}</span>
                      </div>
                    </button>
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}
      </Card>

      {/* Selected format display */}
      {selectedFormat && (
        <div className="mt-2 text-xs text-muted-foreground">
          Selected: <span className="font-medium text-foreground">{selectedFormat.name}</span> (.
          {selectedFormat.extension})
        </div>
      )}
    </div>
  );
}
