import { useState } from 'react'

type PageId = 'overview' | 'scan' | 'process' | 'identify' | 'auto-match' | 'search' | 'modify' | 'tags' | 'faces-maintenance'

export default function Help() {
  const [currentPage, setCurrentPage] = useState<PageId>('overview')

  const renderPageContent = () => {
    switch (currentPage) {
      case 'overview':
        return <NavigationOverview onPageClick={setCurrentPage} />
      case 'scan':
        return <ScanPageHelp onBack={() => setCurrentPage('overview')} />
      case 'process':
        return <ProcessPageHelp onBack={() => setCurrentPage('overview')} />
      case 'identify':
        return <IdentifyPageHelp onBack={() => setCurrentPage('overview')} />
      case 'auto-match':
        return <AutoMatchPageHelp onBack={() => setCurrentPage('overview')} />
      case 'search':
        return <SearchPageHelp onBack={() => setCurrentPage('overview')} />
      case 'modify':
        return <ModifyPageHelp onBack={() => setCurrentPage('overview')} />
      case 'tags':
        return <TagsPageHelp onBack={() => setCurrentPage('overview')} />
      case 'faces-maintenance':
        return <FacesMaintenancePageHelp onBack={() => setCurrentPage('overview')} />
      default:
        return <NavigationOverview onPageClick={setCurrentPage} />
    }
  }

  return (
    <div className="max-w-4xl mx-auto">
      {renderPageContent()}
    </div>
  )
}

function NavigationOverview({ onPageClick }: { onPageClick: (page: PageId) => void }) {
  const navItems = [
    { id: 'scan' as PageId, icon: '🗂️', label: 'Scan', description: 'Import photos from folders or upload files' },
    { id: 'process' as PageId, icon: '⚙️', label: 'Process', description: 'Detect and process faces in photos' },
    { id: 'identify' as PageId, icon: '👤', label: 'Identify', description: 'Manually identify people in faces' },
    { id: 'auto-match' as PageId, icon: '🤖', label: 'Auto-Match', description: 'Automatically match similar faces to previously identified faces' },
    { id: 'search' as PageId, icon: '🔍', label: 'Search', description: 'Search and filter photos' },
    { id: 'modify' as PageId, icon: '✏️', label: 'Modify', description: 'Edit person information' },
    { id: 'tags' as PageId, icon: '🏷️', label: 'Tags', description: 'Tag photos and manage photo tags' },
    { id: 'faces-maintenance' as PageId, icon: '🔧', label: 'Faces Maintenance', description: 'Manage face data' },
  ]

  return (
    <div className="bg-white rounded-lg shadow p-6">
      <h2 className="text-2xl font-bold text-gray-900 mb-4">Navigation Overview</h2>
      <p className="text-gray-700 mb-6">
        The application uses a <strong>left sidebar navigation</strong> with the following pages. Click on any page to learn more about it:
      </p>
      <div className="grid grid-cols-1 gap-3">
        {navItems.map((item) => (
          <button
            key={item.id}
            onClick={() => onPageClick(item.id)}
            className="flex items-center gap-4 p-4 hover:bg-gray-50 rounded-lg border border-gray-200 text-left transition-colors"
          >
            <span className="text-2xl">{item.icon}</span>
            <div className="flex-1">
              <div className="flex items-center gap-2">
                <span className="font-semibold text-gray-900">{item.label}</span>
              </div>
              <p className="text-sm text-gray-600 mt-1">{item.description}</p>
            </div>
            <span className="text-gray-400">→</span>
          </button>
        ))}
      </div>
    </div>
  )
}

function PageHelpLayout({ title, onBack, children }: { title: string; onBack: () => void; children: React.ReactNode }) {
  return (
    <div className="bg-white rounded-lg shadow p-6">
      <div className="flex items-center gap-4 mb-6">
        <button
          onClick={onBack}
          className="px-4 py-2 bg-gray-100 text-gray-700 rounded hover:bg-gray-200 font-medium"
        >
          ← Back
        </button>
        <h2 className="text-2xl font-bold text-gray-900">{title}</h2>
      </div>
      {children}
    </div>
  )
}

function ScanPageHelp({ onBack }: { onBack: () => void }) {
  return (
    <PageHelpLayout title="Scan Page" onBack={onBack}>
      <div className="space-y-4">
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Purpose</h3>
          <p className="text-gray-700">Import photos into your collection from folders or upload files</p>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Features</h3>
          <ul className="list-disc list-inside space-y-1 text-gray-600 ml-4">
            <li><strong>Folder Selection:</strong> Browse and select folders containing photos</li>
            <li><strong>Recursive Scanning:</strong> Option to scan subfolders recursively (enabled by default)</li>
            <li><strong>Duplicate Detection:</strong> Automatically detects and skips duplicate photos</li>
            <li><strong>Real-time Progress:</strong> Live progress tracking during import</li>
            <li><strong>EXIF Extraction:</strong> Automatically extracts date taken and metadata</li>
          </ul>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">How to Use</h3>
          <p className="text-gray-700 font-medium mb-2">Folder Scan:</p>
          <ol className="list-decimal list-inside space-y-1 text-gray-600 ml-4">
            <li>Click "Browse Folder" button</li>
            <li>Select a folder containing photos</li>
            <li>Toggle "Recursive" if you want to include subfolders (enabled by default)</li>
            <li>Click "Start Scan" button</li>
            <li>Monitor progress in the progress bar</li>
            <li>View results (photos added, existing photos skipped)</li>
          </ol>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">What Happens</h3>
          <ul className="list-disc list-inside space-y-1 text-gray-600 ml-4">
            <li>Photos are copied to <code className="bg-gray-100 px-1 rounded">data/uploads</code> directory</li>
            <li>EXIF metadata is extracted (date taken, orientation, etc.)</li>
            <li>Duplicate detection by checksum</li>
            <li>Photos are added to database</li>
            <li>Faces are NOT detected yet (use Process page for that)</li>
          </ul>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Tips</h3>
          <ul className="list-disc list-inside space-y-1 text-gray-600 ml-4">
            <li>Large folders may take time - be patient!</li>
          </ul>
        </div>
      </div>
    </PageHelpLayout>
  )
}

function ProcessPageHelp({ onBack }: { onBack: () => void }) {
  return (
    <PageHelpLayout title="Process Page" onBack={onBack}>
      <div className="space-y-4">
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Purpose</h3>
          <p className="text-gray-700">Detect faces in imported photos and generate face encodings</p>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Features</h3>
          <ul className="list-disc list-inside space-y-1 text-gray-600 ml-4">
            <li><strong>Face detection method used</strong> - <code className="bg-gray-100 px-1 rounded">retinaface</code> - Best accuracy, medium speed</li>
            <li><strong>Face recognition model used</strong> - <code className="bg-gray-100 px-1 rounded">ArcFace</code> - Best accuracy, medium speed</li>
            <li><strong>Batch Size:</strong> Configure how many photos to process at once</li>
            <li><strong>Real-time Progress:</strong> Live progress tracking</li>
            <li><strong>Job Cancellation:</strong> Stop processing if needed</li>
          </ul>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">How to Use</h3>
          <ol className="list-decimal list-inside space-y-1 text-gray-600 ml-4">
            <li>Optionally set <strong>Batch Size</strong> (leave empty for default)</li>
            <li>Click "Start Processing" button</li>
            <li>Monitor progress:
              <ul className="list-disc list-inside ml-4 mt-1">
                <li>Progress bar shows overall completion</li>
                <li>Photo count shows photos processed</li>
                <li>Face count shows faces detected and stored</li>
              </ul>
            </li>
            <li>Wait for completion or click "Stop Processing" to cancel</li>
          </ol>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">What Happens</h3>
          <ul className="list-disc list-inside space-y-1 text-gray-600 ml-4">
            <li>DeepFace analyzes each unprocessed photo</li>
            <li>Faces are detected and located</li>
            <li>512-dimensional face encodings are generated</li>
            <li>Face metadata is stored (confidence, quality, location)</li>
            <li>Photos are marked as processed</li>
          </ul>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Tips</h3>
          <ul className="list-disc list-inside space-y-1 text-gray-600 ml-4">
            <li>You can cancel and resume later</li>
          </ul>
        </div>
      </div>
    </PageHelpLayout>
  )
}

function IdentifyPageHelp({ onBack }: { onBack: () => void }) {
  return (
    <PageHelpLayout title="Identify Page" onBack={onBack}>
      <div className="space-y-4">
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Purpose</h3>
          <p className="text-gray-700">Manually identify people in detected faces</p>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Features</h3>
          <ul className="list-disc list-inside space-y-1 text-gray-600 ml-4">
            <li><strong>Face Navigation:</strong> Browse through unidentified faces</li>
            <li><strong>Person Creation:</strong> Create new person records</li>
            <li><strong>Similar Faces Panel:</strong> View similar faces for comparison</li>
            <li><strong>Confidence Display:</strong> See match confidence percentages</li>
            <li><strong>Date Filtering:</strong> Filter faces by date taken or processed</li>
            <li><strong>Unique Faces Filter:</strong> Hide duplicate faces of same person</li>
            <li><strong>Face Information:</strong> View face metadata (confidence, quality, detector/model)</li>
          </ul>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">How to Use</h3>
          <div className="mb-3">
            <p className="text-gray-700 font-medium mb-2">Basic Identification:</p>
            <ol className="list-decimal list-inside space-y-1 text-gray-600 ml-4">
              <li>Navigate to Identify page</li>
              <li>View the current face on the left panel</li>
              <li>Select existing person from the drop down list or create new person below</li>
              <li>Enter person information:
                <ul className="list-disc list-inside ml-4 mt-1">
                  <li>First Name (required)</li>
                  <li>Last Name (required)</li>
                  <li>Middle Name (optional)</li>
                  <li>Maiden Name (optional)</li>
                  <li>Date of Birth (required)</li>
                </ul>
              </li>
              <li>Click "Identify" button to identify the face</li>
            </ol>
          </div>
          <div className="mb-3">
            <p className="text-gray-700 font-medium mb-2">Using Similar Faces:</p>
            <ol className="list-decimal list-inside space-y-1 text-gray-600 ml-4">
              <li>Toggle "Compare" checkbox to show similar faces</li>
              <li>View similar faces in the right panel</li>
              <li>See confidence percentages (color-coded)</li>
              <li>Select similar faces to bulk identify with the current left face</li>
              <li>Click "Identify" button to bulk identify left and all selected on the right faces to that person.</li>
            </ol>
          </div>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Confidence Colors</h3>
          <ul className="list-disc list-inside space-y-1 text-gray-600 ml-4">
            <li>🟢 <strong>80%+</strong> = Very High (Almost Certain)</li>
            <li>🟡 <strong>70%+</strong> = High (Likely Match)</li>
            <li>🟠 <strong>60%+</strong> = Medium (Possible Match)</li>
            <li>🔴 <strong>50%+</strong> = Low (Questionable)</li>
            <li>⚫ <strong>&lt;50%</strong> = Very Low (Unlikely)</li>
          </ul>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Tips</h3>
          <ul className="list-disc list-inside space-y-1 text-gray-600 ml-4">
            <li>Use similar faces to identify groups of photos</li>
            <li>Date filtering helps focus on specific time periods</li>
            <li>Unique faces filter reduces clutter</li>
            <li>Confidence scores help prioritize identification</li>
          </ul>
        </div>
      </div>
    </PageHelpLayout>
  )
}

function AutoMatchPageHelp({ onBack }: { onBack: () => void }) {
  return (
    <PageHelpLayout title="Auto-Match Page" onBack={onBack}>
      <div className="space-y-4">
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Purpose</h3>
          <p className="text-gray-700">Automatically match unidentified faces to identified people</p>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Features</h3>
          <ul className="list-disc list-inside space-y-1 text-gray-600 ml-4">
            <li><strong>Person-Centric View:</strong> Shows identified person on left, matches on right</li>
            <li><strong>Checkbox Selection:</strong> Select which faces to identify</li>
            <li><strong>Confidence Display:</strong> Color-coded match confidence</li>
            <li><strong>Batch Identification:</strong> Identify multiple faces at once</li>
            <li><strong>Navigation:</strong> Move between different people</li>
          </ul>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">How to Use</h3>
          <div className="mb-3">
            <p className="text-gray-700 font-medium mb-2">Automatic Match Workflow:</p>
            <ol className="list-decimal list-inside space-y-1 text-gray-600 ml-4">
              <li>Navigate to Auto-Match page</li>
              <li>Click Run Auto-Match button</li>
              <li>All unidentified faces will be matched to identified faces based on the following criteria:
                <ul className="list-disc list-inside ml-4 mt-1">
                  <li>Similarity higher than 70%</li>
                  <li>Picture quality higher than 50%</li>
                  <li>Profile faces are excluded for better accuracy</li>
                </ul>
              </li>
            </ol>
          </div>
          <div className="mb-3">
            <p className="text-gray-700 font-medium mb-2">Manual Match Workflow:</p>
            <ol className="list-decimal list-inside space-y-1 text-gray-600 ml-4">
              <li>Navigate to Auto-Match page</li>
              <li>Faces load automatically on page load</li>
              <li>View identified person on the left panel</li>
              <li>View matching unidentified faces on the right panel</li>
              <li>Check boxes next to faces you want to identify</li>
              <li>Click "Save changes for [Person Name]" button</li>
              <li>Use "Next" and "Back" buttons to navigate between people</li>
            </ol>
          </div>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Tips</h3>
          <ul className="list-disc list-inside space-y-1 text-gray-600 ml-4">
            <li>Review matches carefully before saving</li>
            <li>Use confidence scores to guide decisions</li>
            <li>You can correct mistakes by going back and unchecking</li>
            <li>High confidence matches (&gt;70%) are usually accurate</li>
          </ul>
        </div>
      </div>
    </PageHelpLayout>
  )
}

function SearchPageHelp({ onBack }: { onBack: () => void }) {
  return (
    <PageHelpLayout title="Search Page" onBack={onBack}>
      <div className="space-y-4">
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Purpose</h3>
          <p className="text-gray-700">Search and filter photos by various criteria</p>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Features</h3>
          <ul className="list-disc list-inside space-y-1 text-gray-600 ml-4">
            <li><strong>People Filter:</strong> Filter by identified people</li>
            <li><strong>Date Filter:</strong> Filter by date taken or date added</li>
            <li><strong>Tag Filter:</strong> Filter by photo tags</li>
            <li><strong>Folder Filter:</strong> Filter by source folder</li>
            <li><strong>Photo Grid:</strong> Virtualized grid of matching photos</li>
            <li><strong>Pagination:</strong> Navigate through search results</li>
            <li><strong>Select All:</strong> Select all photos in current results</li>
          </ul>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">How to Use</h3>
          <p className="text-gray-700 font-medium mb-2">Basic Search:</p>
          <ol className="list-decimal list-inside space-y-1 text-gray-600 ml-4">
            <li>Navigate to Search page</li>
            <li>Use filter dropdowns to set criteria</li>
            <li>Click "Search" or filters apply automatically</li>
            <li>View matching photos in the grid</li>
            <li>Click on photos to view details</li>
            <li>Use "Select All" to select all photos in results</li>
            <li>Use "Tag selected photos" to tag multiple photos at once</li>
          </ol>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Tips</h3>
          <ul className="list-disc list-inside space-y-1 text-gray-600 ml-4">
            <li>Combine filters for precise searches</li>
            <li>Use date ranges to find photos from specific periods</li>
            <li>Tag filtering helps find themed photos</li>
            <li>People filter is most useful after identification</li>
          </ul>
        </div>
      </div>
    </PageHelpLayout>
  )
}

function ModifyPageHelp({ onBack }: { onBack: () => void }) {
  return (
    <PageHelpLayout title="Modify Page" onBack={onBack}>
      <div className="space-y-4">
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Purpose</h3>
          <p className="text-gray-700">Edit person information and manage person records</p>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Features</h3>
          <ul className="list-disc list-inside space-y-1 text-gray-600 ml-4">
            <li><strong>Person Selection:</strong> Choose person to edit</li>
            <li><strong>Information Editing:</strong> Update names and date of birth</li>
            <li><strong>Face Management:</strong> View and manage person's faces</li>
            <li><strong>Person Deletion:</strong> Remove person records (with confirmation)</li>
          </ul>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">How to Use</h3>
          <p className="text-gray-700 font-medium mb-2">Editing Person Information:</p>
          <ol className="list-decimal list-inside space-y-1 text-gray-600 ml-4">
            <li>Navigate to Modify page</li>
            <li>Select person from dropdown</li>
            <li>Edit information fields (First Name, Last Name, Middle Name, Maiden Name, Date of Birth)</li>
            <li>Click "Save Changes" button</li>
          </ol>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Tips</h3>
          <ul className="list-disc list-inside space-y-1 text-gray-600 ml-4">
            <li>Use this to correct mistakes in identification</li>
            <li>Update names if you learn more information</li>
            <li>Be careful with deletion - it's permanent</li>
          </ul>
        </div>
      </div>
    </PageHelpLayout>
  )
}

function TagsPageHelp({ onBack }: { onBack: () => void }) {
  return (
    <PageHelpLayout title="Tags Page" onBack={onBack}>
      <div className="space-y-4">
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Purpose</h3>
          <p className="text-gray-700">Manage photo tags and tag-photo relationships</p>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Features</h3>
          <ul className="list-disc list-inside space-y-1 text-gray-600 ml-4">
            <li><strong>Tag List:</strong> View all existing tags</li>
            <li><strong>Tag Creation:</strong> Create new tags</li>
            <li><strong>Tag Editing:</strong> Edit tag names</li>
            <li><strong>Tag Deletion:</strong> Remove tags</li>
            <li><strong>Photo-Tag Linkage:</strong> Assign tags to photos</li>
          </ul>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">How to Use</h3>
          <p className="text-gray-700 font-medium mb-2">Creating Tags:</p>
          <ol className="list-decimal list-inside space-y-1 text-gray-600 ml-4">
            <li>Navigate to Tags page</li>
            <li>Click "Manage Tags" button</li>
            <li>Enter new tag name</li>
            <li>Click "Add tag" button</li>
          </ol>
          <p className="text-gray-700 font-medium mb-2 mt-4">Assigning Tags to Photos:</p>
          <ul className="list-disc list-inside space-y-1 text-gray-600 ml-4">
            <li>Select photos from Tags page (or from Search page)</li>
            <li>Tags can be assigned to multiple photos at once by selecting multiple photos and clicking "Tag Selected Photos" button</li>
            <li>Tags can be assigned to all photos in a specific folder at once by clicking the linkage icon next to the folder name</li>
            <li>Tags can be assigned to a single photo by clicking the linkage icon on the right of each photo</li>
          </ul>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Tips</h3>
          <ul className="list-disc list-inside space-y-1 text-gray-600 ml-4">
            <li>Use descriptive tag names</li>
            <li>Create tags for events, locations, themes</li>
            <li>Tags help organize and find photos later</li>
            <li><strong>Note:</strong> Tags are case insensitive!</li>
          </ul>
        </div>
      </div>
    </PageHelpLayout>
  )
}

function FacesMaintenancePageHelp({ onBack }: { onBack: () => void }) {
  return (
    <PageHelpLayout title="Faces Maintenance Page" onBack={onBack}>
      <div className="space-y-4">
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Purpose</h3>
          <p className="text-gray-700">Remove unwanted faces - mainly due to low quality face detections</p>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Features</h3>
          <ul className="list-disc list-inside space-y-1 text-gray-600 ml-4">
            <li><strong>Face List:</strong> View all faces in database</li>
            <li><strong>Face Filtering:</strong> Filter quality</li>
            <li><strong>Face Deletion:</strong> Remove unwanted faces</li>
            <li><strong>Bulk Operations:</strong> Perform actions on multiple faces</li>
          </ul>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">How to Use</h3>
          <p className="text-gray-700 font-medium mb-2">Viewing Faces:</p>
          <ol className="list-decimal list-inside space-y-1 text-gray-600 ml-4">
            <li>Navigate to Faces Maintenance page</li>
            <li>View list of all faces</li>
            <li>See face thumbnails and metadata</li>
            <li>Filter faces by quality (delete faces with low quality)</li>
          </ol>
          <p className="text-gray-700 font-medium mb-2 mt-4">Deleting Faces:</p>
          <ul className="list-disc list-inside space-y-1 text-gray-600 ml-4">
            <li>Select faces to delete</li>
            <li>Click "Delete Selected" button</li>
            <li>Confirm deletion</li>
            <li>⚠️ <strong>Warning:</strong> Deletion is permanent</li>
          </ul>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-800 mb-2">Tips</h3>
          <ul className="list-disc list-inside space-y-1 text-gray-600 ml-4">
            <li>Remove low-quality face detections</li>
            <li>Regular maintenance keeps database clean</li>
          </ul>
        </div>
      </div>
    </PageHelpLayout>
  )
}

