import { useEffect, useState, useRef, useCallback } from 'react'
import peopleApi, { PersonWithFaces, PersonFaceItem, PersonVideoItem, PersonUpdateRequest } from '../api/people'
import facesApi from '../api/faces'
import videosApi from '../api/videos'

interface EditDialogProps {
  person: PersonWithFaces
  onSave: (personId: number, data: PersonUpdateRequest) => Promise<void>
  onClose: () => void
}

function EditPersonDialog({ person, onSave, onClose }: EditDialogProps) {
  const [firstName, setFirstName] = useState(person.first_name || '')
  const [lastName, setLastName] = useState(person.last_name || '')
  const [middleName, setMiddleName] = useState(person.middle_name || '')
  const [maidenName, setMaidenName] = useState(person.maiden_name || '')
  const [dob, setDob] = useState(person.date_of_birth || '')
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const canSave = firstName.trim() && lastName.trim()

  const handleSave = async () => {
    if (!canSave || busy) return

    setBusy(true)
    setError(null)

    try {
      await onSave(person.id, {
        first_name: firstName.trim(),
        last_name: lastName.trim(),
        middle_name: middleName.trim() || undefined,
        maiden_name: maidenName.trim() || undefined,
        date_of_birth: dob.trim() || null,
      })
      onClose()
    } catch (err: any) {
      setError(err.response?.data?.detail || err.message || 'Failed to update person')
    } finally {
      setBusy(false)
    }
  }

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && canSave && !busy) {
      handleSave()
    } else if (e.key === 'Escape') {
      onClose()
    }
  }

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
        <h2 className="text-xl font-bold mb-4">Edit {person.first_name} {person.last_name}</h2>

        {error && (
          <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded text-red-700 text-sm">
            {error}
          </div>
        )}

        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              First name <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={firstName}
              onChange={(e) => setFirstName(e.target.value)}
              onKeyDown={handleKeyDown}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              autoFocus
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Last name <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={lastName}
              onChange={(e) => setLastName(e.target.value)}
              onKeyDown={handleKeyDown}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Middle name</label>
            <input
              type="text"
              value={middleName}
              onChange={(e) => setMiddleName(e.target.value)}
              onKeyDown={handleKeyDown}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Maiden name</label>
            <input
              type="text"
              value={maidenName}
              onChange={(e) => setMaidenName(e.target.value)}
              onKeyDown={handleKeyDown}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Date of birth</label>
            <input
              type="date"
              value={dob}
              onChange={(e) => setDob(e.target.value)}
              onKeyDown={handleKeyDown}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
        </div>

        <div className="mt-6 flex justify-end gap-3">
          <button
            onClick={onClose}
            disabled={busy}
            className="px-4 py-2 text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200 disabled:opacity-50"
          >
            Cancel
          </button>
          <button
            onClick={handleSave}
            disabled={!canSave || busy}
            className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {busy ? 'Saving...' : 'Save'}
          </button>
        </div>
      </div>
    </div>
  )
}

export default function Modify() {
  const [people, setPeople] = useState<PersonWithFaces[]>([])
  const [lastNameFilter, setLastNameFilter] = useState('')
  const [selectedPersonId, setSelectedPersonId] = useState<number | null>(null)
  const [selectedPersonName, setSelectedPersonName] = useState('')
  const [faces, setFaces] = useState<PersonFaceItem[]>([])
  const [videos, setVideos] = useState<PersonVideoItem[]>([])
  const [unmatchConfirmDialog, setUnmatchConfirmDialog] = useState<{
    type: 'face' | 'video'
    single: boolean
    faceId?: number
    videoId?: number
    count?: number
  } | null>(null)
  const [selectedFaces, setSelectedFaces] = useState<Set<number>>(new Set())
  const [selectedVideos, setSelectedVideos] = useState<Set<number>>(new Set())
  const [editDialogPerson, setEditDialogPerson] = useState<PersonWithFaces | null>(null)
  const [deleteDialogPerson, setDeleteDialogPerson] = useState<PersonWithFaces | null>(null)
  const [facesExpanded, setFacesExpanded] = useState(true)
  const [videosExpanded, setVideosExpanded] = useState(false)
  const [peoplePanelWidth, setPeoplePanelWidth] = useState(450) // Default width in pixels (will be set to 50% on mount)
  const [isResizing, setIsResizing] = useState(false)
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)
  const [selectedVideoToPlay, setSelectedVideoToPlay] = useState<PersonVideoItem | null>(null)

  const gridRef = useRef<HTMLDivElement>(null)

  // SessionStorage key for persisting page state (clears when tab/window closes)
  const STATE_KEY = 'modify_state'
  
  // Track if state has been restored from sessionStorage
  const [stateRestored, setStateRestored] = useState(false)
  // Track if initial restoration is complete (prevents reload effects from firing during restoration)
  const restorationCompleteRef = useRef(false)

  // Load people with faces
  const loadPeople = useCallback(async () => {
    try {
      setBusy(true)
      setError(null)
      const res = await peopleApi.listWithFaces(lastNameFilter || undefined)
      setPeople(res.items)
      
      // Auto-select first person if available and none selected (only if not restoring state)
      if (res.items.length > 0 && !selectedPersonId && restorationCompleteRef.current) {
        const firstPerson = res.items[0]
        setSelectedPersonId(firstPerson.id)
        setSelectedPersonName(formatPersonName(firstPerson))
        loadPersonFaces(firstPerson.id)
        loadPersonVideos(firstPerson.id)
      }
    } catch (err: any) {
      setError(err.response?.data?.detail || err.message || 'Failed to load people')
    } finally {
      setBusy(false)
    }
  }, [lastNameFilter, selectedPersonId])

  // Load faces for a person
  const loadPersonFaces = useCallback(async (personId: number) => {
    try {
      setBusy(true)
      setError(null)
      const res = await peopleApi.getFaces(personId)
      setFaces(res.items)
    } catch (err: any) {
      // If person not found (404), clear selection instead of showing error
      // This can happen if person was deleted after selection
      const errorDetail = err.response?.data?.detail || err.message || ''
      if (err.response?.status === 404 && errorDetail.includes('Person') && errorDetail.includes('not found')) {
        setSelectedPersonId(null)
        setSelectedPersonName('')
        setFaces([])
        setVideos([])
        setError(null) // Don't show error for deleted person
      } else {
        setError(errorDetail || 'Failed to load faces')
      }
    } finally {
      setBusy(false)
    }
  }, [])

  // Load videos for a person
  const loadPersonVideos = useCallback(async (personId: number) => {
    try {
      const res = await peopleApi.getVideos(personId)
      setVideos(res.items)
    } catch (err: any) {
      // If person not found, videos will be empty
      if (err.response?.status !== 404) {
        console.error('Failed to load videos:', err)
      }
      setVideos([])
    }
  }, [])

  // Load state from sessionStorage on mount
  useEffect(() => {
    let restoredPanelWidth = false
    try {
      const saved = sessionStorage.getItem(STATE_KEY)
      if (saved) {
        const state = JSON.parse(saved)
        if (state.lastNameFilter !== undefined) {
          setLastNameFilter(state.lastNameFilter || '')
        }
        if (state.selectedPersonId !== undefined && state.selectedPersonId !== null) {
          setSelectedPersonId(state.selectedPersonId)
        }
        if (state.selectedPersonName !== undefined) {
          setSelectedPersonName(state.selectedPersonName || '')
        }
        if (state.faces && Array.isArray(state.faces)) {
          setFaces(state.faces)
        }
        if (state.videos && Array.isArray(state.videos)) {
          setVideos(state.videos)
        }
        if (state.selectedFaces && Array.isArray(state.selectedFaces)) {
          setSelectedFaces(new Set(state.selectedFaces))
        }
        if (state.selectedVideos && Array.isArray(state.selectedVideos)) {
          setSelectedVideos(new Set(state.selectedVideos))
        }
        if (state.facesExpanded !== undefined) {
          setFacesExpanded(state.facesExpanded)
        }
        if (state.videosExpanded !== undefined) {
          setVideosExpanded(state.videosExpanded)
        }
        if (state.peoplePanelWidth !== undefined) {
          setPeoplePanelWidth(state.peoplePanelWidth)
          restoredPanelWidth = true
        }
        // Mark restoration as complete
        setTimeout(() => {
          restorationCompleteRef.current = true
        }, 50)
      } else {
        // No saved state, mark as restored immediately
        restorationCompleteRef.current = true
      }
      
      // Initialize panel width if not restored from state
      if (!restoredPanelWidth) {
        const container = document.querySelector('[data-modify-container]') as HTMLElement
        if (container) {
          const containerWidth = container.getBoundingClientRect().width
          const initialWidth = Math.max(450, containerWidth * 0.5) // At least 450px, or 50% of container
          setPeoplePanelWidth(initialWidth)
        }
      }
    } catch (error) {
      console.error('Error loading state from sessionStorage:', error)
      restorationCompleteRef.current = true
    } finally {
      setStateRestored(true)
    }
     
  }, [])

  useEffect(() => {
    // Only load people if state has been restored
    if (stateRestored) {
      loadPeople()
    }
  }, [loadPeople, stateRestored])

  // Load faces and videos for restored selected person
  useEffect(() => {
    if (stateRestored && selectedPersonId && restorationCompleteRef.current) {
      loadPersonFaces(selectedPersonId)
      loadPersonVideos(selectedPersonId)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [stateRestored, selectedPersonId])


  // Handle resize
  useEffect(() => {
    const handleMouseMove = (e: MouseEvent) => {
      if (!isResizing) return
      const container = document.querySelector('[data-modify-container]') as HTMLElement
      if (!container) return
      const containerRect = container.getBoundingClientRect()
      const newWidth = e.clientX - containerRect.left
      const minWidth = 450 // Minimum width for People panel (current size)
      if (newWidth >= minWidth) {
        setPeoplePanelWidth(newWidth)
      }
    }

    const handleMouseUp = () => {
      setIsResizing(false)
    }

    if (isResizing) {
      document.addEventListener('mousemove', handleMouseMove)
      document.addEventListener('mouseup', handleMouseUp)
      document.body.style.cursor = 'col-resize'
      document.body.style.userSelect = 'none'
    }

    return () => {
      document.removeEventListener('mousemove', handleMouseMove)
      document.removeEventListener('mouseup', handleMouseUp)
      document.body.style.cursor = ''
      document.body.style.userSelect = ''
    }
  }, [isResizing])

  // Save state to sessionStorage whenever it changes (but only after initial restore)
  useEffect(() => {
    if (!stateRestored || !restorationCompleteRef.current) return // Don't save during initial restore
    
    try {
      const state = {
        lastNameFilter,
        selectedPersonId,
        selectedPersonName,
        faces,
        videos,
        selectedFaces: Array.from(selectedFaces),
        selectedVideos: Array.from(selectedVideos),
        facesExpanded,
        videosExpanded,
        peoplePanelWidth,
      }
      sessionStorage.setItem(STATE_KEY, JSON.stringify(state))
    } catch (error) {
      console.error('Error saving state to sessionStorage:', error)
    }
  }, [lastNameFilter, selectedPersonId, selectedPersonName, faces, videos, selectedFaces, selectedVideos, facesExpanded, videosExpanded, peoplePanelWidth, stateRestored])

  // Save state on unmount (when navigating away) - use refs to capture latest values
  const lastNameFilterRef = useRef(lastNameFilter)
  const selectedPersonIdRef = useRef(selectedPersonId)
  const selectedPersonNameRef = useRef(selectedPersonName)
  const facesRef = useRef(faces)
  const videosRef = useRef(videos)
  const selectedFacesRef = useRef(selectedFaces)
  const selectedVideosRef = useRef(selectedVideos)
  const facesExpandedRef = useRef(facesExpanded)
  const videosExpandedRef = useRef(videosExpanded)
  const peoplePanelWidthRef = useRef(peoplePanelWidth)

  // Update refs whenever state changes
  useEffect(() => {
    lastNameFilterRef.current = lastNameFilter
    selectedPersonIdRef.current = selectedPersonId
    selectedPersonNameRef.current = selectedPersonName
    facesRef.current = faces
    videosRef.current = videos
    selectedFacesRef.current = selectedFaces
    selectedVideosRef.current = selectedVideos
    facesExpandedRef.current = facesExpanded
    videosExpandedRef.current = videosExpanded
    peoplePanelWidthRef.current = peoplePanelWidth
  }, [lastNameFilter, selectedPersonId, selectedPersonName, faces, videos, selectedFaces, selectedVideos, facesExpanded, videosExpanded, peoplePanelWidth])

  // Save state on unmount (when navigating away)
  useEffect(() => {
    return () => {
      try {
        const state = {
          lastNameFilter: lastNameFilterRef.current,
          selectedPersonId: selectedPersonIdRef.current,
          selectedPersonName: selectedPersonNameRef.current,
          faces: facesRef.current,
          videos: videosRef.current,
          selectedFaces: Array.from(selectedFacesRef.current),
          selectedVideos: Array.from(selectedVideosRef.current),
          facesExpanded: facesExpandedRef.current,
          videosExpanded: videosExpandedRef.current,
          peoplePanelWidth: peoplePanelWidthRef.current,
        }
        sessionStorage.setItem(STATE_KEY, JSON.stringify(state))
      } catch (error) {
        console.error('Error saving state on unmount:', error)
      }
    }
  }, [])

  // Reload faces and videos when person changes
  useEffect(() => {
    if (selectedPersonId) {
      loadPersonFaces(selectedPersonId)
      loadPersonVideos(selectedPersonId)
      // Clear selected faces and videos when person changes
      setSelectedFaces(new Set())
      setSelectedVideos(new Set())
    } else {
      setFaces([])
      setVideos([])
    }
  }, [selectedPersonId, loadPersonFaces, loadPersonVideos])

  const formatPersonName = (person: PersonWithFaces): string => {
    const parts: string[] = []
    if (person.first_name) parts.push(person.first_name)
    if (person.middle_name) parts.push(person.middle_name)
    if (person.last_name) parts.push(person.last_name)
    if (person.maiden_name) parts.push(`(${person.maiden_name})`)
    const name = parts.join(' ') || 'Unknown'
    if (person.date_of_birth) {
      return `${name} - ${person.date_of_birth}`
    }
    return name
  }

  const handleSearch = () => {
    loadPeople()
  }

  const handleClearSearch = () => {
    setLastNameFilter('')
    // loadPeople will be called by useEffect
  }

  const handlePersonClick = (person: PersonWithFaces) => {
    setSelectedPersonId(person.id)
    setSelectedPersonName(formatPersonName(person))
    loadPersonFaces(person.id)
    loadPersonVideos(person.id)
  }

  const handleEditPerson = (person: PersonWithFaces) => {
    setEditDialogPerson(person)
  }

  const handleSavePerson = async (personId: number, data: PersonUpdateRequest) => {
    await peopleApi.update(personId, data)
    // Reload people list
    await loadPeople()
    // Reload faces and videos if this is the selected person
    if (selectedPersonId === personId) {
      await loadPersonFaces(personId)
      await loadPersonVideos(personId)
    }
    setSuccess('Person information updated successfully')
    setTimeout(() => setSuccess(null), 3000)
  }

  const handleDeletePerson = async () => {
    if (!deleteDialogPerson) return

    try {
      setBusy(true)
      setError(null)
      await peopleApi.delete(deleteDialogPerson.id)
      
      // Clear selection if deleted person was selected
      if (selectedPersonId === deleteDialogPerson.id) {
        setSelectedPersonId(null)
        setSelectedPersonName('')
        setFaces([])
        setVideos([])
      }
      
      // Reload people list
      await loadPeople()
      
      setDeleteDialogPerson(null)
      setSuccess(`Person "${formatPersonName(deleteDialogPerson)}" deleted successfully`)
      setTimeout(() => setSuccess(null), 3000)
    } catch (err: any) {
      setError(err.response?.data?.detail || err.message || 'Failed to delete person')
    } finally {
      setBusy(false)
    }
  }

  const handleToggleFaceSelection = (faceId: number) => {
    const newSelected = new Set(selectedFaces)
    if (newSelected.has(faceId)) {
      newSelected.delete(faceId)
    } else {
      newSelected.add(faceId)
    }
    setSelectedFaces(newSelected)
  }

  const handleSelectAll = () => {
    const allFaceIds = new Set(faces.map(f => f.id))
    setSelectedFaces(allFaceIds)
  }

  const handleUnselectAll = () => {
    setSelectedFaces(new Set())
  }

  const handleBulkUnmatch = () => {
    if (selectedFaces.size === 0) return
    setUnmatchConfirmDialog({
      type: 'face',
      single: false,
      count: selectedFaces.size,
    })
  }

  const confirmUnmatchFace = async () => {
    if (!unmatchConfirmDialog || !selectedPersonId || !unmatchConfirmDialog.faceId) return

    try {
      setBusy(true)
      setError(null)
      setUnmatchConfirmDialog(null)

      // Unmatch the single face
      await facesApi.batchUnmatch({ face_ids: [unmatchConfirmDialog.faceId] })

      // Reload people list to update face counts
      const peopleRes = await peopleApi.listWithFaces(lastNameFilter || undefined)
      setPeople(peopleRes.items)

      // Reload faces
      await loadPersonFaces(selectedPersonId)

      setSuccess('Successfully unlinked face')
      setTimeout(() => setSuccess(null), 3000)
    } catch (err: any) {
      setError(err.response?.data?.detail || err.message || 'Failed to unmatch face')
    } finally {
      setBusy(false)
    }
  }

  const confirmBulkUnmatchFaces = async () => {
    if (!unmatchConfirmDialog || !selectedPersonId || selectedFaces.size === 0) return

    try {
      setBusy(true)
      setError(null)
      setUnmatchConfirmDialog(null)

      // Batch unmatch all selected faces
      const faceIds = Array.from(selectedFaces)
      await facesApi.batchUnmatch({ face_ids: faceIds })

      // Clear selected faces
      setSelectedFaces(new Set())

      // Reload people list to update face counts
      const peopleRes = await peopleApi.listWithFaces(lastNameFilter || undefined)
      setPeople(peopleRes.items)

      // Reload faces
      await loadPersonFaces(selectedPersonId)

      setSuccess(`Successfully unlinked ${faceIds.length} face(s)`)
      setTimeout(() => setSuccess(null), 3000)
    } catch (err: any) {
      setError(err.response?.data?.detail || err.message || 'Failed to unmatch faces')
    } finally {
      setBusy(false)
    }
  }


  const handleUnmatchVideo = (videoId: number) => {
    setUnmatchConfirmDialog({
      type: 'video',
      single: true,
      videoId,
    })
  }

  const confirmUnmatchVideo = async () => {
    if (!unmatchConfirmDialog || !selectedPersonId || !unmatchConfirmDialog.videoId) return

    try {
      setBusy(true)
      setError(null)
      setUnmatchConfirmDialog(null)

      // Unmatch the single video
      await videosApi.removePerson(unmatchConfirmDialog.videoId, selectedPersonId)

      // Reload people list
      const peopleRes = await peopleApi.listWithFaces(lastNameFilter || undefined)
      setPeople(peopleRes.items)

      // Reload videos
      await loadPersonVideos(selectedPersonId)

      setSuccess('Successfully unlinked video')
      setTimeout(() => setSuccess(null), 3000)
    } catch (err: any) {
      setError(err.response?.data?.detail || err.message || 'Failed to unmatch video')
    } finally {
      setBusy(false)
    }
  }

  const handleToggleVideoSelection = (videoId: number) => {
    const newSelected = new Set(selectedVideos)
    if (newSelected.has(videoId)) {
      newSelected.delete(videoId)
    } else {
      newSelected.add(videoId)
    }
    setSelectedVideos(newSelected)
  }

  const handleBulkUnmatchVideos = () => {
    if (selectedVideos.size === 0) return
    setUnmatchConfirmDialog({
      type: 'video',
      single: false,
      count: selectedVideos.size,
    })
  }

  const confirmBulkUnmatchVideos = async () => {
    if (!unmatchConfirmDialog || !selectedPersonId || selectedVideos.size === 0) return

    try {
      setBusy(true)
      setError(null)
      setUnmatchConfirmDialog(null)

      // Unmatch all selected videos
      const videoIds = Array.from(selectedVideos)
      for (const videoId of videoIds) {
        await videosApi.removePerson(videoId, selectedPersonId)
      }

      // Clear selected videos
      setSelectedVideos(new Set())

      // Reload people list
      const peopleRes = await peopleApi.listWithFaces(lastNameFilter || undefined)
      setPeople(peopleRes.items)

      // Reload videos
      await loadPersonVideos(selectedPersonId)

      setSuccess(`Successfully unlinked ${videoIds.length} video(s)`)
      setTimeout(() => setSuccess(null), 3000)
    } catch (err: any) {
      setError(err.response?.data?.detail || err.message || 'Failed to unmatch videos')
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="flex flex-col" data-modify-container style={{ height: 'calc(100vh - 3rem - 2rem)', overflow: 'hidden' }}>

      {error && (
        <div className="p-4 bg-red-50 border border-red-200 rounded text-red-700 flex-shrink-0">
          {error}
        </div>
      )}

      {success && (
        <div className="p-4 bg-green-50 border border-green-200 rounded text-green-700 flex-shrink-0">
          {success}
        </div>
      )}

      <div className="flex flex-1" style={{ minHeight: 0, overflow: 'hidden' }}>
        {/* Left panel: People list */}
        <div style={{ width: `${peoplePanelWidth}px`, minWidth: '450px', minHeight: 0, display: 'flex', flexDirection: 'column', flexShrink: 0 }}>
          <div className="bg-white rounded-lg shadow p-4 h-full flex flex-col" style={{ minHeight: 0, overflow: 'hidden' }}>
            <h2 className="text-lg font-semibold mb-4 flex-shrink-0">People</h2>

            {/* Search controls */}
            <div className="mb-4 flex-shrink-0">
              <div className="flex gap-2 mb-1">
                <input
                  type="text"
                  value={lastNameFilter}
                  onChange={(e) => setLastNameFilter(e.target.value)}
                  onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                  placeholder="Type Last Name or Maiden Name"
                  className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
                <button
                  onClick={handleSearch}
                  className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
                >
                  Search
                </button>
                <button
                  onClick={handleClearSearch}
                  className="px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200"
                >
                  Clear
                </button>
              </div>
              <p className="text-xs text-gray-500">Search by Last Name or Maiden Name</p>
            </div>

            {/* People list */}
            <div className="flex-1" style={{ minHeight: 0, overflowY: 'auto' }}>
              {busy && people.length === 0 ? (
                <div className="text-center text-gray-500 py-8">Loading...</div>
              ) : people.length === 0 ? (
                <div className="text-center text-gray-500 py-8">No people found</div>
              ) : (
                <div className="space-y-2">
                  {people.map((person) => {
                    const isSelected = selectedPersonId === person.id
                    const name = formatPersonName(person)
                    return (
                      <div
                        key={person.id}
                        className={`flex items-center gap-2 p-2 rounded hover:bg-gray-50 cursor-pointer ${
                          isSelected ? 'bg-blue-50 font-semibold' : ''
                        }`}
                      >
                        <button
                          onClick={(e) => {
                            e.stopPropagation()
                            handleEditPerson(person)
                          }}
                          className="text-sm px-2 py-1 hover:bg-gray-200 rounded"
                          title="Update name"
                        >
                          ✏️
                        </button>
                        <div
                          onClick={() => handlePersonClick(person)}
                          className="flex-1"
                        >
                          {name} ({person.face_count})({person.video_count})
                        </div>
                        <button
                          onClick={(e) => {
                            e.stopPropagation()
                            setDeleteDialogPerson(person)
                          }}
                          className="text-sm px-2 py-1 hover:bg-red-100 text-red-600 rounded"
                          title="Delete person"
                          disabled={busy}
                        >
                          🗑️
                        </button>
                      </div>
                    )
                  })}
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Resize handle */}
        <div
          onMouseDown={() => setIsResizing(true)}
          style={{
            width: '4px',
            cursor: 'col-resize',
            backgroundColor: '#e5e7eb',
            flexShrink: 0,
            position: 'relative',
          }}
          className="hover:bg-gray-400 transition-colors"
        >
          <div
            style={{
              position: 'absolute',
              left: '-2px',
              right: '-2px',
              top: 0,
              bottom: 0,
            }}
          />
        </div>

        {/* Right panel: Faces and Videos split horizontally */}
        <div style={{ flex: 1, minWidth: 0, minHeight: 0, display: 'flex', flexDirection: 'column', gap: '1.5rem', marginLeft: '1.5rem' }}>
          {/* Top section: Faces grid */}
          <div className={facesExpanded ? "flex-1" : ""} style={{ minHeight: 0, display: 'flex', flexDirection: 'column', flexShrink: facesExpanded ? 1 : 0 }}>
            <div className={`bg-white rounded-lg shadow p-4 flex flex-col ${facesExpanded ? 'h-full' : ''}`} style={{ minHeight: 0, overflow: 'hidden' }}>
              <div className="flex items-center justify-between mb-4 flex-shrink-0">
                <button
                  onClick={() => setFacesExpanded(!facesExpanded)}
                  className="flex items-center gap-2 hover:bg-gray-100 px-2 py-1 rounded"
                >
                  <span className="text-lg font-semibold">Faces</span>
                  <span>{facesExpanded ? '▼' : '▶'}</span>
                </button>
              {selectedPersonId && (
                <div className="flex gap-2">
                  {faces.length > 0 && (
                    <>
                      <button
                        onClick={handleSelectAll}
                        disabled={busy}
                        className="px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        Select All
                      </button>
                      <button
                        onClick={handleUnselectAll}
                        disabled={busy || selectedFaces.size === 0}
                        className="px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        Unselect All
                      </button>
                      <button
                        onClick={handleBulkUnmatch}
                        disabled={busy || selectedFaces.size === 0}
                        className="px-3 py-1 text-sm bg-red-600 text-white rounded hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        Unmatch Selected
                      </button>
                    </>
                  )}
                </div>
              )}
            </div>

            {facesExpanded && (
              <>
                {selectedPersonId ? (
                  <div className="flex-1" style={{ minHeight: 0, overflowY: 'auto' }}>
                    {busy && faces.length === 0 ? (
                      <div className="text-center text-gray-500 py-8">Loading faces...</div>
                    ) : faces.length === 0 ? (
                      <div className="text-center text-gray-500 py-8">No faces found for this person</div>
                    ) : (
                      <div
                        ref={gridRef}
                        className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4"
                      >
                        {faces.map((face) => (
                          <div key={face.id} className="flex flex-col items-center">
                            <div className="w-20 h-20 mb-2">
                              <img
                                src={`/api/v1/faces/${face.id}/crop`}
                                alt={`Face ${face.id}`}
                                className="w-full h-full object-cover rounded cursor-pointer hover:opacity-80 transition-opacity"
                                onClick={() => {
                                  // Open photo in new window
                                  window.open(`/api/v1/photos/${face.photo_id}/image`, '_blank')
                                }}
                                title="Click to show original photo"
                                onError={(e) => {
                                  e.currentTarget.src = '/placeholder.png'
                                }}
                              />
                            </div>
                            <label className="flex items-center gap-1 cursor-pointer">
                              <input
                                type="checkbox"
                                checked={selectedFaces.has(face.id)}
                                onChange={() => handleToggleFaceSelection(face.id)}
                                className="rounded"
                                disabled={busy}
                              />
                              <span className="text-xs text-gray-700">Select</span>
                            </label>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                ) : (
                  <div className="flex-1 flex items-center justify-center">
                    <div className="text-center text-gray-500 py-8">
                      Select a person to view their faces
                    </div>
                  </div>
                )}
              </>
            )}
            </div>
          </div>

          {/* Bottom section: Videos list */}
          <div className={videosExpanded ? "flex-1" : ""} style={{ minHeight: 0, display: 'flex', flexDirection: 'column', flexShrink: videosExpanded ? 1 : 0 }}>
            <div className={`bg-white rounded-lg shadow p-4 flex flex-col ${videosExpanded ? 'h-full' : ''}`} style={{ minHeight: 0, overflow: 'hidden' }}>
              <div className="flex items-center justify-between mb-4 flex-shrink-0">
                <button
                  onClick={() => setVideosExpanded(!videosExpanded)}
                  className="flex items-center gap-2 hover:bg-gray-100 px-2 py-1 rounded"
                >
                  <span className="text-lg font-semibold">Videos</span>
                  <span>{videosExpanded ? '▼' : '▶'}</span>
                </button>
                {selectedPersonId && videosExpanded && (
                  <div className="flex gap-2">
                    {videos.length > 0 && (
                      <>
                        <button
                          onClick={() => {
                            const allVideoIds = new Set(videos.map(v => v.id))
                            setSelectedVideos(allVideoIds)
                          }}
                          disabled={busy}
                          className="px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                          Select All
                        </button>
                        <button
                          onClick={() => setSelectedVideos(new Set())}
                          disabled={busy || selectedVideos.size === 0}
                          className="px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                          Unselect All
                        </button>
                        <button
                          onClick={handleBulkUnmatchVideos}
                          disabled={busy || selectedVideos.size === 0}
                          className="px-3 py-1 text-sm bg-red-600 text-white rounded hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                          Unmatch Selected
                        </button>
                      </>
                    )}
                  </div>
                )}
              </div>
              {videosExpanded && (
              <>
                {selectedPersonId ? (
                  <div className="flex-1" style={{ minHeight: 0, overflowY: 'auto' }}>
                    {videos.length === 0 ? (
                      <div className="text-center text-gray-500 py-8">No videos found for this person</div>
                    ) : (
                      <div className="space-y-2">
                        {videos.map((video) => (
                          <div
                            key={video.id}
                            className="p-3 border border-gray-200 rounded hover:bg-gray-50"
                          >
                            <div className="flex items-center gap-2">
                              <input
                                type="checkbox"
                                checked={selectedVideos.has(video.id)}
                                onChange={() => handleToggleVideoSelection(video.id)}
                                className="rounded"
                                disabled={busy}
                                onClick={(e) => e.stopPropagation()}
                              />
                              <div
                                className="flex-1 cursor-pointer"
                                onClick={() => {
                                  // Open video player modal
                                  setSelectedVideoToPlay(video)
                                }}
                                title="Click to play video"
                              >
                                <div className="font-medium text-sm truncate">{video.filename}</div>
                                {video.date_taken && (
                                  <div className="text-xs text-gray-500 mt-1">
                                    {new Date(video.date_taken).toLocaleDateString()}
                                  </div>
                                )}
                              </div>
                              <button
                                onClick={(e) => {
                                  e.stopPropagation()
                                  handleUnmatchVideo(video.id)
                                }}
                                className="px-2 py-1 text-xs bg-red-600 text-white rounded hover:bg-red-700 disabled:opacity-50"
                                disabled={busy}
                                title="Unmatch video"
                              >
                                Unmatch
                              </button>
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                ) : (
                  <div className="flex-1 flex items-center justify-center">
                    <div className="text-center text-gray-500 py-8">
                      Select a person to view their videos
                    </div>
                  </div>
                )}
              </>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Edit person dialog */}
      {editDialogPerson && (
        <EditPersonDialog
          person={editDialogPerson}
          onSave={handleSavePerson}
          onClose={() => setEditDialogPerson(null)}
        />
      )}

      {/* Delete confirmation dialog */}
      {deleteDialogPerson && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
            <h2 className="text-xl font-bold mb-4 text-red-600">Delete Person</h2>
            <p className="mb-4">
              Are you sure you want to delete <strong>{formatPersonName(deleteDialogPerson)}</strong>?
            </p>
            <p className="mb-4 text-sm text-gray-600">
              This will:
              <ul className="list-disc list-inside mt-2 space-y-1">
                <li>Unlink all faces from this person</li>
                <li>Remove all video linkages</li>
                <li>Delete all person encodings</li>
                <li>Permanently delete the person record</li>
              </ul>
            </p>
            <p className="mb-6 text-sm font-semibold text-red-600">
              This action cannot be undone.
            </p>
            <div className="flex justify-end gap-3">
              <button
                onClick={() => setDeleteDialogPerson(null)}
                disabled={busy}
                className="px-4 py-2 text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200 disabled:opacity-50"
              >
                Cancel
              </button>
              <button
                onClick={handleDeletePerson}
                disabled={busy}
                className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {busy ? 'Deleting...' : 'Delete'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Unmatch confirmation dialog */}
      {unmatchConfirmDialog && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
            <h2 className="text-xl font-bold mb-4 text-red-600">Confirm Unmatch</h2>
            <p className="mb-4">
              {unmatchConfirmDialog.single
                ? `Are you sure you want to unmatch this ${unmatchConfirmDialog.type === 'face' ? 'face' : 'video'} from ${selectedPersonName || 'this person'}?`
                : `Are you sure you want to unmatch ${unmatchConfirmDialog.count} ${unmatchConfirmDialog.type === 'face' ? 'face(s)' : 'video(s)'} from ${selectedPersonName || 'this person'}?`}
            </p>
            <p className="mb-6 text-sm text-gray-600">
              This action cannot be undone.
            </p>
            <div className="flex justify-end gap-3">
              <button
                onClick={() => setUnmatchConfirmDialog(null)}
                disabled={busy}
                className="px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Cancel
              </button>
              <button
                onClick={() => {
                  if (unmatchConfirmDialog.type === 'face') {
                    if (unmatchConfirmDialog.single) {
                      confirmUnmatchFace()
                    } else {
                      confirmBulkUnmatchFaces()
                    }
                  } else {
                    if (unmatchConfirmDialog.single) {
                      confirmUnmatchVideo()
                    } else {
                      confirmBulkUnmatchVideos()
                    }
                  }
                }}
                disabled={busy}
                className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {busy ? 'Processing...' : 'Confirm'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Video player modal */}
      {selectedVideoToPlay && (
        <div className="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50" onClick={() => setSelectedVideoToPlay(null)}>
          <div className="bg-black rounded-lg shadow-xl w-full max-w-4xl p-4" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-xl font-bold text-white">{selectedVideoToPlay.filename}</h2>
              <button
                onClick={() => setSelectedVideoToPlay(null)}
                className="text-white hover:text-gray-300 text-2xl font-bold"
                title="Close"
              >
                ×
              </button>
            </div>
            <video
              src={videosApi.getVideoUrl(selectedVideoToPlay.id)}
              controls
              autoPlay
              className="w-full max-h-[80vh] rounded"
            >
              Your browser does not support the video tag.
            </video>
            {selectedVideoToPlay.date_taken && (
              <div className="text-sm text-gray-300 mt-2">
                Date taken: {new Date(selectedVideoToPlay.date_taken).toLocaleDateString()}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  )
}

