'use client'

import { useState, useMemo } from 'react'
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Download, Search, Filter, X, Coffee, Utensils, Package, Droplet, Eye } from 'lucide-react'
import type { Manual, ManualGroup } from '@/lib/manuals-types'
import { getManualUrl } from '@/lib/manuals-types'
import { getMachineTypeInfo, getAllMachineTypeNames } from '@/lib/manuals-config'
import { ManualViewer } from '@/components/manual-viewer'

interface ManualsPageClientProps {
  manuals: Manual[]
  groupedManuals: ManualGroup[]
  manufacturers: string[]
  categories: string[]
}

export function ManualsPageClient({
  manuals,
  groupedManuals,
  manufacturers,
  categories,
}: ManualsPageClientProps) {
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedManufacturer, setSelectedManufacturer] = useState<string>('')
  const [selectedCategory, setSelectedCategory] = useState<string>('')
  const [viewMode, setViewMode] = useState<'grouped' | 'list'>('grouped')
  const [viewingManual, setViewingManual] = useState<{ url: string; filename: string } | null>(null)

  // Filter manuals based on search and filters
  const filteredManuals = useMemo(() => {
    let filtered = manuals

    if (selectedManufacturer) {
      filtered = filtered.filter((m) => m.manufacturer === selectedManufacturer)
    }

    if (selectedCategory) {
      filtered = filtered.filter((m) => m.category === selectedCategory)
    }

    if (searchTerm) {
      const search = searchTerm.toLowerCase()
      filtered = filtered.filter(
        (m) =>
          m.filename.toLowerCase().includes(search) ||
          m.manufacturer.toLowerCase().includes(search) ||
          m.category.toLowerCase().includes(search)
      )
    }

    return filtered
  }, [manuals, searchTerm, selectedManufacturer, selectedCategory])

  // Filter grouped manuals
  const filteredGroupedManuals = useMemo(() => {
    if (!selectedManufacturer && !selectedCategory && !searchTerm) {
      return groupedManuals
    }

    return groupedManuals
      .filter((group) => {
        if (selectedManufacturer && group.manufacturer !== selectedManufacturer) {
          return false
        }
        return true
      })
      .map((group) => {
        const filteredCategories: { [key: string]: Manual[] } = {}
        for (const [category, categoryManuals] of Object.entries(group.categories)) {
          if (selectedCategory && category !== selectedCategory) {
            continue
          }
          const filtered = categoryManuals.filter((manual) => {
            if (searchTerm) {
              const search = searchTerm.toLowerCase()
              return (
                manual.filename.toLowerCase().includes(search) ||
                manual.manufacturer.toLowerCase().includes(search) ||
                manual.category.toLowerCase().includes(search)
              )
            }
            return true
          })
          if (filtered.length > 0) {
            filteredCategories[category] = filtered
          }
        }
        return {
          ...group,
          categories: filteredCategories,
        }
      })
      .filter((group) => Object.keys(group.categories).length > 0)
  }, [groupedManuals, selectedManufacturer, selectedCategory, searchTerm])

  const hasActiveFilters = selectedManufacturer || selectedCategory || searchTerm

  const clearFilters = () => {
    setSearchTerm('')
    setSelectedManufacturer('')
    setSelectedCategory('')
  }

  const formatFileSize = (bytes?: number): string => {
    if (!bytes) return 'Unknown size'
    if (bytes < 1024) return `${bytes} B`
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
  }

  // Organize categories by machine type first, then others
  const organizeCategories = (categories: { [key: string]: Manual[] }) => {
    const machineTypes = getAllMachineTypeNames()
    const machineTypeCategories: { [key: string]: Manual[] } = {}
    const otherCategories: { [key: string]: Manual[] } = {}

    for (const [category, manuals] of Object.entries(categories)) {
      if (machineTypes.includes(category)) {
        machineTypeCategories[category] = manuals
      } else {
        otherCategories[category] = manuals
      }
    }

    // Sort machine types by priority order
    const sortedMachineTypes = machineTypes
      .filter((type) => machineTypeCategories[type])
      .map((type) => [type, machineTypeCategories[type]] as [string, Manual[]])

    // Sort other categories alphabetically
    const sortedOthers = Object.entries(otherCategories).sort(([a], [b]) =>
      a.localeCompare(b)
    )

    return { machineTypes: sortedMachineTypes, others: sortedOthers }
  }

  // Get icon for machine type
  const getCategoryIcon = (category: string) => {
    const machineType = getMachineTypeInfo(category)
    if (!machineType) return null

    switch (category) {
      case 'Coffee':
        return <Coffee className="h-4 w-4" />
      case 'Food':
        return <Utensils className="h-4 w-4" />
      case 'Beverage':
        return <Droplet className="h-4 w-4" />
      case 'Snack':
        return <Package className="h-4 w-4" />
      default:
        return null
    }
  }

  // Get badge color for category
  const getCategoryBadgeClass = (category: string): string => {
    const machineType = getMachineTypeInfo(category)
    const categoryLower = category.toLowerCase()

    // Check for common category patterns
    if (categoryLower.includes('snack')) {
      return 'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200'
    }
    if (categoryLower.includes('beverage') || categoryLower.includes('drink')) {
      return 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200'
    }
    if (categoryLower.includes('frozen')) {
      return 'bg-indigo-100 text-indigo-800 dark:bg-indigo-900 dark:text-indigo-200'
    }
    if (categoryLower.includes('combo')) {
      return 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200'
    }
    if (categoryLower.includes('coffee') || categoryLower.includes('hot')) {
      return 'bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200'
    }
    if (categoryLower.includes('food')) {
      return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
    }
    if (categoryLower.includes('bulk')) {
      return 'bg-pink-100 text-pink-800 dark:bg-pink-900 dark:text-pink-200'
    }
    if (categoryLower.includes('ice') || categoryLower.includes('cream')) {
      return 'bg-cyan-100 text-cyan-800 dark:bg-cyan-900 dark:text-cyan-200'
    }
    if (categoryLower.includes('service') || categoryLower.includes('repair')) {
      return 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200'
    }
    if (categoryLower.includes('parts')) {
      return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200'
    }
    if (categoryLower.includes('operator') || categoryLower.includes('user')) {
      return 'bg-teal-100 text-teal-800 dark:bg-teal-900 dark:text-teal-200'
    }
    if (categoryLower.includes('installation') || categoryLower.includes('setup')) {
      return 'bg-lime-100 text-lime-800 dark:bg-lime-900 dark:text-lime-200'
    }

    // Fallback for machine types
    if (machineType) {
      switch (category) {
        case 'Snack':
          return 'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200'
        case 'Beverage':
          return 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200'
        case 'Combo':
          return 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200'
        case 'Coffee':
          return 'bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200'
        case 'Food':
          return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
        case 'Bulk':
          return 'bg-pink-100 text-pink-800 dark:bg-pink-900 dark:text-pink-200'
        case 'Ice Cream':
          return 'bg-cyan-100 text-cyan-800 dark:bg-cyan-900 dark:text-cyan-200'
        default:
          return 'bg-muted text-muted-foreground'
      }
    }

    return 'bg-muted text-muted-foreground'
  }

  return (
    <div className="space-y-6">
      {/* Search and Filter Controls */}
      <Card>
        <CardContent className="pt-6">
          <div className="space-y-4">
            {/* Search Bar */}
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
              <Input
                type="text"
                placeholder="Search manuals by name, manufacturer, or category..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>

            {/* Filters */}
            <div className="flex flex-wrap gap-4 items-center">
              <div className="flex items-center gap-2">
                <Filter className="h-4 w-4 text-muted-foreground" />
                <span className="text-sm font-medium">Filters:</span>
              </div>

              <select
                value={selectedManufacturer}
                onChange={(e) => setSelectedManufacturer(e.target.value)}
                className="h-9 rounded-md border border-input bg-background px-3 py-1 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
              >
                <option value="">All Manufacturers</option>
                {manufacturers.map((mfr) => (
                  <option key={mfr} value={mfr}>
                    {mfr}
                  </option>
                ))}
              </select>

              <select
                value={selectedCategory}
                onChange={(e) => setSelectedCategory(e.target.value)}
                className="h-9 rounded-md border border-input bg-background px-3 py-1 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
              >
                <option value="">All Categories</option>
                {categories.map((cat) => (
                  <option key={cat} value={cat}>
                    {cat}
                  </option>
                ))}
              </select>

              {hasActiveFilters && (
                <Button variant="outline" size="sm" onClick={clearFilters}>
                  <X className="h-4 w-4 mr-1" />
                  Clear Filters
                </Button>
              )}
            </div>

            {/* View Mode Toggle */}
            <div className="flex items-center gap-2">
              <span className="text-sm text-muted-foreground">View:</span>
              <Button
                variant={viewMode === 'grouped' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setViewMode('grouped')}
              >
                Grouped
              </Button>
              <Button
                variant={viewMode === 'list' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setViewMode('list')}
              >
                List
              </Button>
            </div>

            {/* Results Count */}
            <div className="text-sm text-muted-foreground">
              Showing <strong>{filteredManuals.length}</strong> of <strong>{manuals.length}</strong>{' '}
              manuals
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Manuals Display */}
      {filteredManuals.length === 0 ? (
        <Card>
          <CardContent className="py-12 text-center">
            <p className="text-muted-foreground">
              No manuals found matching your criteria. Try adjusting your filters.
            </p>
          </CardContent>
        </Card>
      ) : viewMode === 'grouped' ? (
        /* Grouped View */
        <div className="space-y-8">
          {filteredGroupedManuals.map((group) => {
            const organized = organizeCategories(group.categories)
            return (
              <div key={group.manufacturer} className="space-y-6">
                <h2 className="text-2xl font-bold border-b pb-2">{group.manufacturer}</h2>
                
                {/* Machine Type Categories First */}
                {organized.machineTypes.length > 0 && (
                  <div className="space-y-4">
                    {organized.machineTypes.map(([category, categoryManuals]) => {
                      const machineTypeInfo = getMachineTypeInfo(category)
                      const icon = getCategoryIcon(category)
                      return (
                        <div key={category} className="space-y-3">
                          <div className="flex items-center gap-2">
                            {icon && <span className="text-muted-foreground">{icon}</span>}
                            <h3 className="text-lg font-semibold">{category}</h3>
                            <span
                              className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${getCategoryBadgeClass(
                                category
                              )}`}
                            >
                              {categoryManuals.length} {categoryManuals.length === 1 ? 'manual' : 'manuals'}
                            </span>
                            {machineTypeInfo && (
                              <span className="text-sm text-muted-foreground">
                                {machineTypeInfo.description}
                              </span>
                            )}
                          </div>
                          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            {categoryManuals.map((manual) => (
                              <Card key={manual.path} className="hover:shadow-md transition-shadow">
                                <CardHeader>
                                  <CardTitle className="text-base line-clamp-2">
                                    {manual.filename.replace(/\.pdf$/i, '')}
                                  </CardTitle>
                                </CardHeader>
                                <CardContent className="space-y-3">
                                  <div className="flex flex-wrap gap-2">
                                    <span
                                      className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${getCategoryBadgeClass(
                                        manual.category
                                      )}`}
                                    >
                                      {manual.category}
                                    </span>
                                  </div>
                                  <div className="text-sm text-muted-foreground space-y-1">
                                    {manual.size && (
                                      <p>
                                        <strong>Size:</strong> {formatFileSize(manual.size)}
                                      </p>
                                    )}
                                  </div>
                                  <div className="flex items-center gap-2">
                                    <Button
                                      variant="outline"
                                      size="sm"
                                      onClick={() => setViewingManual({ url: getManualUrl(manual), filename: manual.filename })}
                                      className="flex-1"
                                    >
                                      <Eye className="h-4 w-4 mr-1" />
                                      View PDF
                                    </Button>
                                    <a
                                      href={getManualUrl(manual)}
                                      target="_blank"
                                      rel="noopener noreferrer"
                                      className="inline-flex items-center gap-2 text-sm font-medium text-primary hover:underline px-2"
                                    >
                                      <Download className="h-4 w-4" />
                                    </a>
                                  </div>
                                </CardContent>
                              </Card>
                            ))}
                          </div>
                        </div>
                      )
                    })}
                  </div>
                )}

                {/* Other Categories (Model Numbers, Document Types, etc.) */}
                {organized.others.length > 0 && (
                  <div className="space-y-4">
                    {organized.machineTypes.length > 0 && (
                      <h3 className="text-lg font-semibold text-muted-foreground border-t pt-4">
                        Models & Other Documents
                      </h3>
                    )}
                    {organized.others.map(([category, categoryManuals]) => (
                      <div key={category} className="space-y-2">
                        <div className="flex items-center gap-2">
                          <h4 className="text-base font-semibold text-muted-foreground">
                            {category}
                          </h4>
                          <span className="text-xs text-muted-foreground">
                            ({categoryManuals.length} {categoryManuals.length === 1 ? 'manual' : 'manuals'})
                          </span>
                        </div>
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                          {categoryManuals.map((manual) => (
                            <Card key={manual.path} className="hover:shadow-md transition-shadow">
                              <CardHeader>
                                <CardTitle className="text-base line-clamp-2">
                                  {manual.filename.replace(/\.pdf$/i, '')}
                                </CardTitle>
                              </CardHeader>
                              <CardContent className="space-y-3">
                                <div className="flex flex-wrap gap-2">
                                  <span
                                    className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${getCategoryBadgeClass(
                                      manual.category
                                    )}`}
                                  >
                                    {manual.category}
                                  </span>
                                </div>
                                <div className="text-sm text-muted-foreground space-y-1">
                                  {manual.size && (
                                    <p>
                                      <strong>Size:</strong> {formatFileSize(manual.size)}
                                    </p>
                                  )}
                                </div>
                                <div className="flex items-center gap-2">
                                  <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={() => setViewingManual({ url: getManualUrl(manual), filename: manual.filename })}
                                    className="flex-1"
                                  >
                                    <Eye className="h-4 w-4 mr-1" />
                                    View PDF
                                  </Button>
                                  <a
                                    href={getManualUrl(manual)}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="inline-flex items-center gap-2 text-sm font-medium text-primary hover:underline px-2"
                                  >
                                    <Download className="h-4 w-4" />
                                  </a>
                                </div>
                              </CardContent>
                            </Card>
                          ))}
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )
          })}
        </div>
      ) : (
        /* List View */
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filteredManuals.map((manual) => (
            <Card key={manual.path} className="hover:shadow-md transition-shadow">
              <CardHeader>
                <CardTitle className="text-base line-clamp-2">
                  {manual.filename.replace(/\.pdf$/i, '')}
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="flex flex-wrap gap-2">
                  <span
                    className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${getCategoryBadgeClass(
                      manual.category
                    )}`}
                  >
                    {manual.category}
                  </span>
                </div>
                <div className="text-sm text-muted-foreground space-y-1">
                  <p>
                    <strong>Manufacturer:</strong> {manual.manufacturer}
                  </p>
                  {manual.size && (
                    <p>
                      <strong>Size:</strong> {formatFileSize(manual.size)}
                    </p>
                  )}
                </div>
                <div className="flex items-center gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setViewingManual({ url: getManualUrl(manual), filename: manual.filename })}
                    className="flex-1"
                  >
                    <Eye className="h-4 w-4 mr-1" />
                    View PDF
                  </Button>
                  <a
                    href={getManualUrl(manual)}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-2 text-sm font-medium text-primary hover:underline px-2"
                  >
                    <Download className="h-4 w-4" />
                  </a>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* PDF Viewer Modal */}
      {viewingManual && (
        <ManualViewer
          manualUrl={viewingManual.url}
          filename={viewingManual.filename}
          isOpen={!!viewingManual}
          onClose={() => setViewingManual(null)}
        />
      )}
    </div>
  )
}

