'use client';

import { useState, useCallback } from 'react';
import {
  xTwitterApi,
  projectsApi,
  TweetPreview,
  CreateFromTweetPayload,
  Project,
} from '@/lib/api/api-service';

interface UseTweetState {
  preview: TweetPreview | null;
  isLoadingPreview: boolean;
  isCreatingProject: boolean;
  error: string | null;
  createdProject: Project | null;
}

/**
 * X/Twitter tweet import hook.
 * 1. URL ön izleme: tweet çeker, viral skor hesaplar, prompt önerir
 * 2. Proje oluşturma: tweet'ten otomatik proje + senaryo üretir
 */
export function useTweet() {
  const [state, setState] = useState<UseTweetState>({
    preview: null,
    isLoadingPreview: false,
    isCreatingProject: false,
    error: null,
    createdProject: null,
  });

  /**
   * Tweet URL validasyonu (client-side)
   */
  const isValidTweetUrl = useCallback((url: string): boolean => {
    return /^https?:\/\/(x\.com|twitter\.com)\/([\w]+\/status\/\d+|i\/status\/\d+)/.test(url);
  }, []);

  /**
   * Tweet ön izleme — URL'yi backend'e gönder, tweet verisi + viral skor al
   */
  const previewTweet = useCallback(async (tweetUrl: string) => {
    if (!isValidTweetUrl(tweetUrl)) {
      setState((prev) => ({
        ...prev,
        error: 'Geçerli bir X/Twitter URL\'si girin (https://x.com/user/status/123)',
        preview: null,
      }));
      return null;
    }

    setState((prev) => ({
      ...prev,
      isLoadingPreview: true,
      error: null,
      preview: null,
      createdProject: null,
    }));

    try {
      const response = await xTwitterApi.preview(tweetUrl);
      const preview = response && typeof response === 'object' && 'data' in response
        ? (response as { data: TweetPreview }).data
        : response;

      setState((prev) => ({
        ...prev,
        preview,
        isLoadingPreview: false,
      }));
      return preview;
    } catch (err) {
      const message =
        err instanceof Error
          ? err.message
          : 'Tweet çekilemedi. URL\'yi kontrol edin.';
      setState((prev) => ({
        ...prev,
        error: message,
        isLoadingPreview: false,
      }));
      return null;
    }
  }, [isValidTweetUrl]);

  /**
   * Tweet'ten proje oluştur — ön izleme sonrasında
   */
  const createProjectFromTweet = useCallback(
    async (payload: CreateFromTweetPayload) => {
      setState((prev) => ({
        ...prev,
        isCreatingProject: true,
        error: null,
      }));

      try {
        const response = await projectsApi.createFromTweet(payload);
        const project = response && typeof response === 'object' && 'data' in response
          ? (response as { data: Project }).data
          : response;

        setState((prev) => ({
          ...prev,
          createdProject: project,
          isCreatingProject: false,
        }));
        return project;
      } catch (err) {
        const message =
          err instanceof Error
            ? err.message
            : 'Tweet\'ten proje oluşturulamadı.';
        setState((prev) => ({
          ...prev,
          error: message,
          isCreatingProject: false,
        }));
        return null;
      }
    },
    [],
  );

  /**
   * State'i temizle — yeni import için
   */
  const reset = useCallback(() => {
    setState({
      preview: null,
      isLoadingPreview: false,
      isCreatingProject: false,
      error: null,
      createdProject: null,
    });
  }, []);

  return {
    ...state,
    isValidTweetUrl,
    previewTweet,
    createProjectFromTweet,
    reset,
  };
}
