'use client';

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

export default function AppsPage() {
  const [user, setUser] = useState<User | null>(null);
  const [apps, setApps] = useState<GeneratedApp[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [filterType, setFilterType] = useState<string>('all');
  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 apps
    fetch('/api/apps')
      .then(res => res.json())
      .then(data => {
        if (data.apps) {
          setApps(data.apps);
        }
      })
      .catch(console.error)
      .finally(() => setIsLoading(false));
  }, [router]);

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

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

      if (response.ok) {
        setApps(apps.filter(a => a.id !== id));
      }
    } catch (error) {
      console.error('Failed to delete app:', error);
    }
  };

  const filteredApps = filterType === 'all'
    ? apps
    : apps.filter(app => app.appType === filterType);

  const appTypes = Array.from(new Set(apps.map(a => a.appType).filter(Boolean)));

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

            {appTypes.length > 0 && (
              <div className="bg-white border rounded-lg p-4 mb-6">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Filter by Type
                </label>
                <select
                  value={filterType}
                  onChange={(e) => setFilterType(e.target.value)}
                  className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="all">All Apps</option>
                  {appTypes.map(type => (
                    <option key={type} value={type}>{type}</option>
                  ))}
                </select>
              </div>
            )}

            <AppGallery
              apps={filteredApps}
              isLoading={isLoading}
              onSelectApp={handleSelectApp}
            />
          </div>
        </main>
      </div>
    </div>
  );
}
