import { useState, useEffect, useMemo, useCallback } from 'react';
import { useAuth } from '@{{PROJECT_NAME}}/auth';
import { useMediaUpload } from '@{{PROJECT_NAME}}/realtime';
import {
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
  MediaUploader,
  MediaLibrary,
  type MediaItem,
  Badge,
} from '@{{PROJECT_NAME}}/ui';

export function MediaPage() {
  const { getToken } = useAuth();
  const [items, setItems] = useState<MediaItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [deleteError, setDeleteError] = useState<string | null>(null);

  const apiPrefix = import.meta.env.VITE_API_URL || '';

  const authHeaders = useMemo(() => {
    const token = getToken();
    return token ? { Authorization: `Bearer ${token}` } : undefined;
  }, [getToken]);

  const mediaUpload = useMediaUpload({
    apiPrefix,
    serviceName: '{{SERVICE_NAME}}',
    headers: authHeaders,
  });

  const [fetchError, setFetchError] = useState<string | null>(null);

  const fetchMedia = useCallback(async () => {
    setFetchError(null);
    try {
      const res = await fetch(`${apiPrefix}/api/{{SERVICE_NAME}}/media`, {
        headers: { ...authHeaders },
      });
      if (!res.ok) {
        setFetchError(`Failed to load media (${res.status})`);
        return;
      }
      const data = await res.json();
      setItems(data.items || []);
    } catch (err) {
      setFetchError(err instanceof Error ? err.message : 'Failed to load media');
    } finally {
      setIsLoading(false);
    }
  }, [apiPrefix, authHeaders]);

  useEffect(() => {
    fetchMedia();
  }, [fetchMedia]);

  const handleUploadComplete = useCallback(() => {
    fetchMedia();
  }, [fetchMedia]);

  const handleDelete = useCallback(async (id: string) => {
    setDeleteError(null);
    try {
      const res = await fetch(`${apiPrefix}/api/{{SERVICE_NAME}}/media/${id}`, {
        method: 'DELETE',
        headers: { ...authHeaders },
      });
      if (!res.ok) throw new Error(`Delete failed: ${res.status}`);
      setItems((prev) => prev.filter((item) => item.id !== id));
    } catch (err) {
      setDeleteError(err instanceof Error ? err.message : 'Delete failed');
    }
  }, [apiPrefix, authHeaders]);

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>Upload Media</CardTitle>
          <CardDescription>
            Upload images and videos to your media library
          </CardDescription>
        </CardHeader>
        <CardContent>
          <MediaUploader
            upload={mediaUpload.upload}
            isUploading={mediaUpload.isUploading}
            progress={mediaUpload.progress}
            onUploadComplete={handleUploadComplete}
            onError={(err) => console.error('Upload error:', err)}
          />
          {mediaUpload.error && (
            <p className="mt-2 text-sm text-[var(--error)]">{mediaUpload.error}</p>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <div>
            <CardTitle>Media Library</CardTitle>
            <CardDescription>
              Your uploaded and generated media files
            </CardDescription>
          </div>
          {items.length > 0 && (
            <Badge variant="outline">{items.length} files</Badge>
          )}
        </CardHeader>
        <CardContent>
          {(deleteError || fetchError) && (
            <p className="mb-4 text-sm text-[var(--error)]">{deleteError || fetchError}</p>
          )}
          {isLoading ? (
            <div className="text-center py-8 text-[var(--text-muted)]">Loading...</div>
          ) : (
            <MediaLibrary
              items={items}
              onDelete={handleDelete}
            />
          )}
        </CardContent>
      </Card>
    </div>
  );
}
