"use client";

import { useState, useEffect } from "react";
import { countTwitterChars, countWeightedLength } from "@/lib/twitter-text";

interface ThreadEditorProps {
  content: string;
  onChange: (chunks: string[]) => void;
}

/** Split text into tweet-sized chunks at sentence boundaries */
function splitIntoTweets(text: string, maxLen = 280): string[] {
  if (countTwitterChars(text) <= maxLen) return [text];

  const chunks: string[] = [];
  let remaining = text;

  while (remaining.length > 0) {
    if (countTwitterChars(remaining) <= maxLen) {
      chunks.push(remaining);
      break;
    }

    const segment = remaining.slice(0, maxLen);
    // Try to break at sentence boundary (. or \n)
    let splitAt = -1;
    for (let i = segment.length - 1; i >= Math.floor(maxLen * 0.5); i--) {
      if (segment[i] === "." || segment[i] === "\n") {
        splitAt = i + 1;
        break;
      }
    }
    // Fall back to last space
    if (splitAt === -1) {
      for (let i = segment.length - 1; i >= Math.floor(maxLen * 0.5); i--) {
        if (segment[i] === " ") {
          splitAt = i + 1;
          break;
        }
      }
    }
    // Last resort: hard cut
    if (splitAt === -1) splitAt = maxLen;

    chunks.push(remaining.slice(0, splitAt).trim());
    remaining = remaining.slice(splitAt).trim();
  }

  return chunks;
}

export function ThreadEditor({ content, onChange }: ThreadEditorProps) {
  const [chunks, setChunks] = useState<string[]>(() => splitIntoTweets(content));

  useEffect(() => {
    setChunks(splitIntoTweets(content));
  }, [content]);

  const updateChunk = (index: number, value: string) => {
    const next = [...chunks];
    next[index] = value;
    setChunks(next);
    onChange(next);
  };

  const addChunk = () => {
    const next = [...chunks, ""];
    setChunks(next);
    onChange(next);
  };

  const total = chunks.length;

  return (
    <div className="rounded-lg border border-blue-200 bg-blue-50/50 p-3 space-y-3">
      <p className="text-xs font-medium text-blue-700">
        Twitter Thread — {total} tweet{total !== 1 ? "s" : ""}
      </p>
      {chunks.map((chunk, i) => (
        <div key={i} className="space-y-1">
          <div className="flex items-center justify-between">
            <span className="text-[10px] font-medium text-blue-600">
              {i + 1}/{total}
            </span>
            <span className={`text-[10px] ${countTwitterChars(chunk) > 280 ? "text-red-500 font-medium" : "text-gray-400"}`}>
              {countTwitterChars(chunk)}/280
            </span>
          </div>
          <textarea
            value={chunk}
            onChange={(e) => updateChunk(i, e.target.value)}
            className="w-full min-h-[60px] rounded-md border border-blue-200 bg-white px-2.5 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400 resize-y"
          />
        </div>
      ))}
      <button
        type="button"
        onClick={addChunk}
        className="text-xs font-medium text-blue-600 hover:text-blue-700 hover:underline"
      >
        + Add tweet
      </button>
    </div>
  );
}
