import React, { useState } from 'react';
import { useAppDispatch, useAppSelector } from '../app/hooks';
import { copyToClipboard } from '../utils/clipboard';
import { normalizeUrl, isValidUrlForShortening } from '../utils/url';
import {
    shortenUrl,
    selectShortUrl,
    selectUrlStatus,
    selectUrlError,
    clearShortUrl,
} from '../features/url/urlSlice';

const Home: React.FC = () => {
    /* component level state */
    const [url, setUrl] = useState('');
    const [urlError, setUrlError] = useState('');

    /* global state */
    const dispatch = useAppDispatch();
    const shortUrl = useAppSelector(selectShortUrl);
    const status = useAppSelector(selectUrlStatus);
    const error = useAppSelector(selectUrlError);

    /* methods */
    const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
        if (e.key === 'Enter') {
            handleSubmit();
        }
    };

    const handleSubmit = () => {
        if (url.trim() !== '') {
            if (!isValidUrlForShortening(url)) {
                setUrlError('Hmm, that URL doesn’t look right. Try something like https://example.com.');
                dispatch(clearShortUrl())
            } else {
                setUrlError('');
                dispatch(shortenUrl(normalizeUrl(url)));
            }
        }
    };

    const handleCopy = () => {
        if (shortUrl) {
            copyToClipboard(shortUrl)
                .then(() => console.log('Copied!'))
                .catch((err) => console.error('Copy failed', err));
        }
    };

    const handleClear = () => {
        setUrl('')
        dispatch(clearShortUrl())
    };

    return (
        <div className="min-h-screen bg-purple-100 px-4 py-10 flex flex-col items-center">
            {/* Top Section (Static Position) */}
            <div className="text-center space-y-6">
                <h1 className="text-5xl text-orange-500 font-pacifico">minxa.lol</h1>

                <div className="flex items-center justify-center space-x-2">
                    <input
                        type="text"
                        placeholder="https://example.com/my-long-url"
                        value={url}
                        onChange={(e) => setUrl(e.target.value)}
                        onKeyDown={handleKeyDown}
                        className="w-80 p-3 rounded-md text-lg border border-gray-300 shadow-sm focus:outline-none focus:ring-2 focus:ring-orange-400"
                    />
                    <button
                        onClick={handleSubmit}
                        className="w-12 h-12 bg-orange-500 text-white text-xl font-bold rounded-md hover:bg-orange-600 transition"
                    >
                        ↵
                    </button>
                </div>

                {urlError && (
                    <p className="text-red-600 text-sm">{urlError}</p>
                )}

                {status === 'loading' && (
                    <p className="text-gray-600 text-sm">Shortening your URL...</p>
                )}

                {status === 'failed' && (
                    <p className="text-red-600 text-sm">{error}</p>
                )}
            </div>

            {/* Spacer to ensure result doesn't push up the input */}
            <div className="h-10" />

            {/* Result Section (Appears Below) */}
            {status === 'succeeded' && shortUrl && (
                <div className="w-full max-w-md border-t border-gray-300 pt-6 text-center">
                    <p className="text-green-700 font-medium text-lg">
                        Your short URL:
                        <a
                            href={shortUrl}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="underline ml-2"
                        >
                            {shortUrl}
                        </a>
                    </p>
                    <div className="flex justify-center space-x-2 mt-4">
                        <button
                            onClick={handleCopy}
                            className="bg-orange-500 text-white px-4 py-2 rounded hover:bg-orange-600 transition"
                        >
                            Copy to Clipboard
                        </button>
                        <button
                            onClick={handleClear}
                            className="bg-gray-300 text-gray-800 px-4 py-2 rounded hover:bg-gray-400 transition"
                        >
                            Clear
                        </button>
                    </div>
                </div>
            )}
        </div>
    );
};

export default Home;

