"use client";

import { useState, useRef } from 'react';
import Image from 'next/image';
import { X, Upload } from 'lucide-react';
import '@/styles/Auth.css';

export default function SaljaMobler() {
    const [formData, setFormData] = useState({
        name: '',
        address: '',
        email: '',
        phone: '',
        message: '',
    });
    const [images, setImages] = useState<File[]>([]);
    const [imagePreviews, setImagePreviews] = useState<string[]>([]);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [submitStatus, setSubmitStatus] = useState<'success' | 'error' | null>(null);
    const [errorMessage, setErrorMessage] = useState('');
    const fileInputRef = useRef<HTMLInputElement>(null);

    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        setFormData(prev => ({
            ...prev,
            [e.target.name]: e.target.value
        }));
    };

    const handleImageSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
        const files = e.target.files;
        if (!files) return;

        const newFiles = Array.from(files);
        const totalImages = images.length + newFiles.length;

        if (totalImages > 4) {
            setErrorMessage('Max 4 bilder tillåtna');
            setTimeout(() => setErrorMessage(''), 3000);
            return;
        }

        // Validate file sizes
        for (const file of newFiles) {
            if (file.size > 5 * 1024 * 1024) {
                setErrorMessage('Bilderna får max vara 5MB vardera');
                setTimeout(() => setErrorMessage(''), 3000);
                return;
            }
            if (!file.type.startsWith('image/')) {
                setErrorMessage('Endast bildfiler tillåtna');
                setTimeout(() => setErrorMessage(''), 3000);
                return;
            }
        }

        setImages(prev => [...prev, ...newFiles]);

        // Create previews
        newFiles.forEach(file => {
            const reader = new FileReader();
            reader.onloadend = () => {
                setImagePreviews(prev => [...prev, reader.result as string]);
            };
            reader.readAsDataURL(file);
        });

        // Reset input
        if (fileInputRef.current) {
            fileInputRef.current.value = '';
        }
    };

    const removeImage = (index: number) => {
        setImages(prev => prev.filter((_, i) => i !== index));
        setImagePreviews(prev => prev.filter((_, i) => i !== index));
    };

    const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        setIsSubmitting(true);
        setSubmitStatus(null);
        setErrorMessage('');

        try {
            const formPayload = new FormData();
            formPayload.append('name', formData.name);
            formPayload.append('address', formData.address);
            formPayload.append('email', formData.email);
            formPayload.append('phone', formData.phone);
            formPayload.append('message', formData.message);

            images.forEach(image => {
                formPayload.append('images', image);
            });

            const res = await fetch('/api/sell-furniture', {
                method: 'POST',
                body: formPayload,
            });

            const data = await res.json();

            if (res.ok) {
                setSubmitStatus('success');
                setFormData({ name: '', address: '', email: '', phone: '', message: '' });
                setImages([]);
                setImagePreviews([]);
            } else {
                setSubmitStatus('error');
                setErrorMessage(data.error || 'Något gick fel. Försök igen.');
            }
        } catch (err) {
            console.error('Sell furniture form error:', err);
            setSubmitStatus('error');
            setErrorMessage('Kunde inte skicka meddelandet. Försök igen senare.');
        } finally {
            setIsSubmitting(false);
            setTimeout(() => {
                setSubmitStatus(null);
                setErrorMessage('');
            }, 5000);
        }
    };

    return (
        <div className="auth-page-container">
            <div className="card-xl" style={{ width: '100%', maxWidth: '1200px' }}>
                {/* Hero Section */}
                <div style={{
                    display: 'grid',
                    gridTemplateColumns: '1fr',
                    gap: '3rem',
                    alignItems: 'center',
                    marginBottom: '4rem',
                    paddingBottom: '3rem',
                    borderBottom: '1px solid var(--border-color)'
                }} className="hero-grid">
                    <div style={{ position: 'relative', width: '100%', height: '300px', borderRadius: '8px', overflow: 'hidden' }}>
                        <Image
                            src="/artifacts/sell_furniture_hero.webp"
                            alt="Sälja Möbler"
                            fill
                            style={{ objectFit: 'cover' }}
                            priority
                        />
                    </div>

                    <div>
                        <h1 className="auth-title" style={{ textAlign: 'left', marginBottom: '1.5rem', fontSize: '2.5rem' }}>
                            Sälja Dina Kontorsmöbler
                        </h1>
                        <div style={{ fontSize: '0.95rem', lineHeight: '1.8', color: 'var(--text-color)' }}>
                            <p style={{ marginBottom: '1.5rem' }}>
                                Ge dina begagnade kontorsmöbler ett nytt liv! Istället för att kasta möblerna kan du sälja dem till oss.
                            </p>
                            <div style={{
                                background: 'var(--card-bg)',
                                padding: '1.5rem',
                                border: '2px solid var(--border-color)',
                                marginBottom: '1.5rem'
                            }}>
                                <p style={{ fontSize: '0.85rem', fontWeight: '900', textTransform: 'uppercase', letterSpacing: '1px', marginBottom: '1rem' }}>
                                    Vi tar hand om hela processen:
                                </p>
                                <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
                                    <li style={{ marginBottom: '0.75rem', paddingLeft: '1.5rem', position: 'relative' }}>
                                        <span style={{ position: 'absolute', left: 0 }}>✓</span>
                                        Värdering och köp av dina möbler
                                    </li>
                                    <li style={{ marginBottom: '0.75rem', paddingLeft: '1.5rem', position: 'relative' }}>
                                        <span style={{ position: 'absolute', left: 0 }}>✓</span>
                                        Hjälp med inköp av nya möbler
                                    </li>
                                    <li style={{ paddingLeft: '1.5rem', position: 'relative' }}>
                                        <span style={{ position: 'absolute', left: 0 }}>✓</span>
                                        Hållbar och miljövänlig lösning
                                    </li>
                                </ul>
                            </div>
                            <p style={{ fontSize: '0.9rem', fontWeight: '600' }}>
                                Skicka in information och bilder på dina möbler nedan, så hör vi av oss!
                            </p>
                        </div>
                    </div>
                </div>

                {/* Form Card */}
                <div className="profile-card">
                    <h3 className="auth-subtitle" style={{ marginBottom: '2rem' }}>Skicka Ditt Förslag</h3>

                    <form onSubmit={handleSubmit}>
                        <div className="form-group" style={{ position: 'relative', marginBottom: '1.5rem' }}>
                            <input
                                type="text"
                                name="name"
                                placeholder="Namn"
                                className="form-input"
                                value={formData.name}
                                onChange={handleChange}
                                required
                            />
                        </div>

                        <div className="form-group" style={{ position: 'relative', marginBottom: '1.5rem' }}>
                            <input
                                type="text"
                                name="address"
                                placeholder="Adress"
                                className="form-input"
                                value={formData.address}
                                onChange={handleChange}
                                required
                            />
                        </div>

                        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem', marginBottom: '1.5rem' }} className="form-row">
                            <div className="form-group" style={{ position: 'relative' }}>
                                <input
                                    type="email"
                                    name="email"
                                    placeholder="E-post"
                                    className="form-input"
                                    value={formData.email}
                                    onChange={handleChange}
                                    required
                                />
                            </div>

                            <div className="form-group" style={{ position: 'relative' }}>
                                <input
                                    type="tel"
                                    name="phone"
                                    placeholder="Telefonnummer"
                                    className="form-input"
                                    value={formData.phone}
                                    onChange={handleChange}
                                    required
                                />
                            </div>
                        </div>

                        <div className="form-group" style={{ position: 'relative', marginBottom: '2rem' }}>
                            <textarea
                                name="message"
                                placeholder="Meddelande (beskriv möblerna, tillstånd, etc.)"
                                className="form-input"
                                value={formData.message}
                                onChange={handleChange}
                                required
                                rows={6}
                                style={{ resize: 'vertical', minHeight: '180px', paddingTop: '1.2rem' }}
                            />
                        </div>

                        {/* Image Upload Section */}
                        <div style={{ marginBottom: '2rem' }}>
                            <p style={{
                                fontSize: '0.85rem',
                                fontWeight: '900',
                                textTransform: 'uppercase',
                                letterSpacing: '1px',
                                marginBottom: '1rem',
                                color: 'var(--text-secondary)'
                            }}>
                                Bilder ({images.length}/4)
                            </p>

                            {imagePreviews.length > 0 && (
                                <div style={{
                                    display: 'grid',
                                    gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))',
                                    gap: '1rem',
                                    marginBottom: '1rem'
                                }}>
                                    {imagePreviews.map((preview, index) => (
                                        <div key={index} style={{ position: 'relative', aspectRatio: '1', border: '2px solid var(--border-color)', borderRadius: '4px', overflow: 'hidden' }}>
                                            <img
                                                src={preview}
                                                alt={`Preview ${index + 1}`}
                                                style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                                            />
                                            <button
                                                type="button"
                                                onClick={() => removeImage(index)}
                                                style={{
                                                    position: 'absolute',
                                                    top: '0.5rem',
                                                    right: '0.5rem',
                                                    background: 'rgba(0,0,0,0.7)',
                                                    border: 'none',
                                                    borderRadius: '50%',
                                                    width: '28px',
                                                    height: '28px',
                                                    display: 'flex',
                                                    alignItems: 'center',
                                                    justifyContent: 'center',
                                                    cursor: 'pointer',
                                                    color: 'white'
                                                }}
                                            >
                                                <X size={16} />
                                            </button>
                                        </div>
                                    ))}
                                </div>
                            )}

                            {images.length < 4 && (
                                <>
                                    <input
                                        ref={fileInputRef}
                                        type="file"
                                        accept="image/*"
                                        multiple
                                        onChange={handleImageSelect}
                                        style={{ display: 'none' }}
                                        id="image-upload"
                                    />
                                    <button
                                        type="button"
                                        onClick={() => fileInputRef.current?.click()}
                                        className="auth-button secondary"
                                        style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '0.5rem' }}
                                    >
                                        <Upload size={20} />
                                        {images.length === 0 ? 'Ladda upp bilder' : 'Ladda upp fler bilder'}
                                    </button>
                                </>
                            )}
                        </div>

                        <button type="submit" className="auth-button primary" disabled={isSubmitting} style={{ width: '100%' }}>
                            {isSubmitting ? 'Skickar...' : 'Skicka Förfrågan'}
                        </button>

                        {submitStatus === 'success' && (
                            <div className="auth-success" style={{ marginTop: '1.5rem' }}>
                                Tack för ditt meddelande! Vi återkommer så snart vi kan.
                            </div>
                        )}
                        {(submitStatus === 'error' || errorMessage) && (
                            <div className="auth-error" style={{ marginTop: '1.5rem' }}>
                                {errorMessage || 'Något gick fel. Försök igen.'}
                            </div>
                        )}
                    </form>
                </div>
            </div>

            <style jsx>{`
        @media (min-width: 900px) {
          .hero-grid {
            grid-template-columns: 450px 1fr !important;
          }
          .form-row {
            grid-template-columns: 1fr 1fr !important;
          }
        }
        
        @media (max-width: 899px) {
          .hero-grid {
            grid-template-columns: 1fr !important;
          }
          .form-row {
            grid-template-columns: 1fr !important;
          }
        }
      `}</style>
        </div>
    );
}
