'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Header from '../components/Header';
import Sidebar from '../components/Sidebar';
import RecordingList from '../components/RecordingList';
import type { User, Recording } from '@/types';

export default function RecordingsPage() {
  const [user, setUser] = useState<User | null>(null);
  const [recordings, setRecordings] = useState<Recording[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState<'date' | 'title'>('date');
  const router = useRouter();

  useEffect(() => {
    // Fetch current user
    fetch('/api/auth/me')
      .then(res => {
        if (!res.ok) {
          router.push('/login');
          return null;
        }
        return res.json();
      })
      .then(data => {
        if (data) setUser(data);
      })
      .catch(() => router.push('/login'));

    // Fetch recordings
    fetch('/api/recordings')
      .then(res => res.json())
      .then(data => {
        if (data.recordings) {
          setRecordings(data.recordings);
        }
      })
      .catch(console.error)
      .finally(() => setIsLoading(false));
  }, [router]);

  const handleSelectRecording = (id: string) => {
    router.push(`/recordings/${id}`);
  };

  const handleDeleteRecording = async (id: string) => {
    try {
      const response = await fetch(`/api/recordings/${id}`, {
        method: 'DELETE',
      });

      if (response.ok) {
        setRecordings(recordings.filter(r => r.id !== id));
      }
    } catch (error) {
      console.error('Failed to delete recording:', error);
    }
  };

  const filteredRecordings = recordings.filter(r =>
    r.title.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const sortedRecordings = [...filteredRecordings].sort((a, b) => {
    if (sortBy === 'date') {
      return new Date(b.createdAt ?? '').getTime() - new Date(a.createdAt ?? '').getTime();
    } else {
      return a.title.localeCompare(b.title);
    }
  });

  return (
    <div className="flex min-h-screen bg-gray-50">
      <Sidebar activePath="/recordings" />
      <div className="flex-1">
        <Header user={user} />
        <main className="p-6">
          <div className="max-w-4xl mx-auto">
            <h1 className="text-3xl font-bold text-gray-900 mb-6">Recordings</h1>

            <div className="bg-white border rounded-lg p-4 mb-6 flex gap-4">
              <input
                type="text"
                placeholder="Search recordings..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
              <select
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value as 'date' | 'title')}
                className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="date">Sort by Date</option>
                <option value="title">Sort by Title</option>
              </select>
            </div>

            <RecordingList
              recordings={sortedRecordings}
              isLoading={isLoading}
              onSelectRecording={handleSelectRecording}
              onDeleteRecording={handleDeleteRecording}
            />
          </div>
        </main>
      </div>
    </div>
  );
}
