'use client';

import { useState } from 'react';
import axios from 'axios';
import { API_BASE_URL } from '../../../lib/api-config';

type CreateLinkProps = {
    onCreated: () => Promise<void>;
}

export default function ShortenerBox({onCreated} : CreateLinkProps) {
    const [longUrl, setLongUrl] = useState('');
    const [result, setResult] = useState<any>(null);
    const [loading, setLoading] = useState(false);
    const [limitReached, setLimitReached] = useState<string | null>(null);

    const handleShrink = async (e: React.FormEvent) => {
        e.preventDefault();
        setLimitReached(null)

        if (!longUrl) {
            alert("please enter a valid link");
        }

        setLoading(true);

        const token = document.cookie
          .split('; ')
          .find((row) => row.startsWith('wtihub_token='))
          ?.split('=')[1];

        if (!token) {
            alert("wtihub-session-error: You must be logged in to shrink links.");
            setLoading(false);
            return;
        }

        try {
            const response = await axios.post(`${API_BASE_URL}/api/shrink`, {
                originalUrl: longUrl
            },
            {
                headers: {
                    Authorization: `Bearer ${token}`
                }
            });

            setResult(response.data.data);
            setLongUrl('');
            if (onCreated) await onCreated();
        } catch (error: any) {
            if (axios.isAxiosError(error)) {
                const status = error.response?.status;
                const message = error.response?.data.message;

                if (status === 403) {
                    setLimitReached(message);
                    alert(limitReached) 
                    setResult(null); 
                    return;
                } else if (status === 401) {
                    alert("wtihub-error: Session expired. Please login again.");
                } else {
                    alert(`wtihub-error: ${message || "Could not process link."}`);
                }
            }
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="bg-wtihub-surface border border-wtihub-border p-8 rounded-xl shadow-2xl max-w-3xl mx-auto mt-12">
            <h2 className="text-xl font-bold mb-4 text-wtihub-green">Create New Stream</h2>

            <form onSubmit={handleShrink} className="flex flex-col md:flex-row gap-4">
                <input
                  type="url"
                  placeholder="Paste your long destination URL here..."
                  className="flex-1 bg-wtihub-bg border border-wtihub-border p-4 rounded-lg text-wtihub-text focus:outline-none focus:border-wtihub-green transition-all"
                  value={longUrl}
                  onChange={(e) => setLongUrl(e.target.value)}
                  required
                  />
                  <button 
                    type="submit"
                    disabled={loading}
                    className="btn-wtihub disabled:opacity-50"
                    >
                        {loading ? 'Processing..' : 'Shrink Now'}
                    </button>
            </form>

            {result && (
                <div className="mt-8 p-6 bg-wtihub-bg rounded-lg border border-wtihub-green/30 animate-in fade-in slide-in-from-bottom-4">
                    <div className="flex flex-col md:flex-row items-center gap-8">
                        {/* left: link details */}
                        <div className="flex-1">
                            <p className="text-sm text-gray-400 mb-1">Your Short Link:</p>
                            <a href={result.shortUrl} target="_blank" className="text-wtihub-green font-mono text-lg break-all hover:underline">
                                {result.shortUrl}
                            </a>
                            <button onClick={() => navigator.clipboard.writeText(result.shortUrl).then(() => alert("Link Copied"))} className="block mt-4 text-xs bg-wtihub-surface px-3 py-1 ronded border border-wtihub-border hover:bg-wtihub-border">
                                Copy to Clipboard
                            </button>
                        </div>

                        {/*right: the python-generated qr*/}
                        {result.wtihub_qr_code && (
                            <div className="text-center">
                                <img src={result.wtihub_qr_code} alt="wtihub QR" className="w-32 h-32 rounded-lg border-2 border-wtihub-green shadow-lg" />
                                <p className="text-[10px] mt-2 uppercase tracking-widest text-gray-500">wtihub-pixel-engine</p>
                            </div>
                        )}
                    </div>
                </div>
            )}
        </div>
    )
}