import React, { useState, useRef } from 'react';
import { X, Bug, Lightbulb, Send, Loader, CheckCircle, AlertCircle, Image, Trash2 } from 'lucide-react';

// ⚠️ CONVENTION: Use relative API path from REACT_APP_API_BASE only — the hardcoded fallback 'http://localhost:3001/api' is an absolute URL. Other components use just the env var without an absolute fallback.
const API_BASE = process.env.REACT_APP_API_BASE || 'http://localhost:3001/api';

// ---------------------------------------------------------------------------
// Styles
// ---------------------------------------------------------------------------
const backdropStyle = {
  position: 'fixed', inset: 0,
  background: 'rgba(0,0,0,0.6)',
  backdropFilter: 'blur(3px)',
  zIndex: 60,
  display: 'flex', alignItems: 'center', justifyContent: 'center',
};

const modalStyle = {
  width: '480px', maxWidth: '90vw', maxHeight: '85vh',
  background: 'linear-gradient(135deg, #0F1A2E 0%, #1E293B 100%)',
  border: '1px solid rgba(14,165,233,0.2)',
  borderRadius: '0.75rem',
  boxShadow: '0 24px 64px rgba(0,0,0,0.7)',
  display: 'flex', flexDirection: 'column',
  overflow: 'hidden',
};

const headerStyle = {
  padding: '1.25rem 1.5rem',
  borderBottom: '1px solid rgba(255,255,255,0.06)',
  display: 'flex', justifyContent: 'space-between', alignItems: 'center',
};

const bodyStyle = {
  padding: '1.5rem',
  overflowY: 'auto', flex: 1,
};

const labelStyle = {
  display: 'block',
  fontSize: '0.72rem',
  fontFamily: "'JetBrains Mono', monospace",
  color: '#94A3B8',
  marginBottom: '0.4rem',
  textTransform: 'uppercase',
  letterSpacing: '0.05em',
};

const inputStyle = {
  width: '100%', boxSizing: 'border-box',
  background: 'rgba(14,165,233,0.06)',
  border: '1px solid rgba(14,165,233,0.2)',
  borderRadius: '0.375rem',
  color: '#E2E8F0',
  padding: '0.6rem 0.75rem',
  fontSize: '0.82rem',
  fontFamily: "'JetBrains Mono', monospace",
  outline: 'none',
  transition: 'border-color 0.15s',
};

const textareaStyle = {
  ...inputStyle,
  minHeight: '120px',
  resize: 'vertical',
  lineHeight: 1.5,
};

const btnStyle = {
  display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: '0.5rem',
  padding: '0.6rem 1.25rem',
  borderRadius: '0.375rem',
  fontSize: '0.78rem',
  fontFamily: "'JetBrains Mono', monospace",
  fontWeight: 600,
  cursor: 'pointer',
  transition: 'all 0.15s',
  border: 'none',
  textTransform: 'uppercase',
  letterSpacing: '0.05em',
};

// ---------------------------------------------------------------------------
// Type selector tabs
// ---------------------------------------------------------------------------
function TypeSelector({ value, onChange }) {
  const types = [
    { id: 'bug', label: 'Bug Report', icon: Bug, color: '#EF4444' },
    { id: 'feature', label: 'Feature Request', icon: Lightbulb, color: '#F59E0B' },
  ];

  return (
    <div style={{ display: 'flex', gap: '0.5rem', marginBottom: '1.25rem' }}>
      {types.map(({ id, label, icon: Icon, color }) => {
        const active = value === id;
        return (
          <button
            key={id}
            type="button"
            onClick={() => onChange(id)}
            style={{
              flex: 1,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '0.5rem',
              padding: '0.65rem 0.75rem',
              borderRadius: '0.375rem',
              border: active ? `1px solid ${color}` : '1px solid rgba(255,255,255,0.08)',
              background: active ? `${color}15` : 'transparent',
              color: active ? color : '#64748B',
              fontSize: '0.75rem',
              fontFamily: "'JetBrains Mono', monospace",
              fontWeight: 600,
              cursor: 'pointer',
              transition: 'all 0.15s',
              textTransform: 'uppercase',
              letterSpacing: '0.04em',
            }}
          >
            <Icon style={{ width: 14, height: 14 }} />
            {label}
          </button>
        );
      })}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Screenshot thumbnails
// ---------------------------------------------------------------------------
function ScreenshotPreviews({ files, onRemove }) {
  if (files.length === 0) return null;

  return (
    <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap', marginTop: '0.5rem' }}>
      {files.map((file, idx) => (
        <div
          key={idx}
          style={{
            position: 'relative',
            width: '64px', height: '64px',
            borderRadius: '0.375rem',
            overflow: 'hidden',
            border: '1px solid rgba(14,165,233,0.2)',
            background: 'rgba(14,165,233,0.06)',
          }}
        >
          <img
            src={URL.createObjectURL(file)}
            alt={file.name}
            style={{ width: '100%', height: '100%', objectFit: 'cover' }}
          />
          <button
            type="button"
            onClick={() => onRemove(idx)}
            style={{
              position: 'absolute', top: '2px', right: '2px',
              width: '18px', height: '18px',
              borderRadius: '50%',
              background: 'rgba(239,68,68,0.9)',
              border: 'none',
              cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              padding: 0,
            }}
            title="Remove screenshot"
          >
            <Trash2 style={{ width: 10, height: 10, color: '#fff' }} />
          </button>
        </div>
      ))}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Main modal component
// ---------------------------------------------------------------------------
const MAX_FILES = 3;
const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
const ACCEPTED_TYPES = 'image/png,image/jpeg,image/gif,image/webp';

export default function FeedbackModal({ isOpen, onClose, defaultType, currentPage }) {
  const [type, setType] = useState(defaultType || 'bug');
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [screenshots, setScreenshots] = useState([]);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(null);
  const fileInputRef = useRef(null);

  if (!isOpen) return null;

  const handleFileChange = (e) => {
    const newFiles = Array.from(e.target.files || []);
    setError(null);

    // Validate file count
    const totalFiles = screenshots.length + newFiles.length;
    if (totalFiles > MAX_FILES) {
      setError(`Maximum ${MAX_FILES} screenshots allowed`);
      e.target.value = '';
      return;
    }

    // Validate file sizes
    for (const file of newFiles) {
      if (file.size > MAX_FILE_SIZE) {
        setError(`"${file.name}" exceeds 5MB limit`);
        e.target.value = '';
        return;
      }
    }

    setScreenshots(prev => [...prev, ...newFiles]);
    e.target.value = '';
  };

  const handleRemoveScreenshot = (idx) => {
    setScreenshots(prev => prev.filter((_, i) => i !== idx));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!title.trim() || !description.trim()) {
      setError('Title and description are required');
      return;
    }

    setSubmitting(true);
    setError(null);
    try {
      const formData = new FormData();
      formData.append('type', type);
      formData.append('title', title.trim());
      formData.append('description', description.trim());
      if (currentPage) {
        formData.append('page', currentPage);
      }
      for (const file of screenshots) {
        formData.append('screenshots', file);
      }

      const res = await fetch(`${API_BASE}/feedback`, {
        method: 'POST',
        credentials: 'include',
        body: formData,
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || `Submission failed (${res.status})`);

      setSuccess(data.issue);
      setTitle('');
      setDescription('');
      setScreenshots([]);
    } catch (err) {
      setError(err.message);
    } finally {
      setSubmitting(false);
    }
  };

  const handleClose = () => {
    setError(null);
    setSuccess(null);
    setTitle('');
    setDescription('');
    setScreenshots([]);
    onClose();
  };

  const typeColor = type === 'bug' ? '#EF4444' : '#F59E0B';

  return (
    <div style={backdropStyle} onClick={handleClose}>
      <div style={modalStyle} onClick={e => e.stopPropagation()}>
        {/* Header */}
        <div style={headerStyle}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
            {type === 'bug'
              ? <Bug style={{ width: 18, height: 18, color: '#EF4444' }} />
              : <Lightbulb style={{ width: 18, height: 18, color: '#F59E0B' }} />
            }
            <span style={{
              fontSize: '0.9rem', fontWeight: 700, color: '#E2E8F0',
              fontFamily: "'JetBrains Mono', monospace",
            }}>
              {type === 'bug' ? 'Report a Bug' : 'Request a Feature'}
            </span>
          </div>
          <button
            onClick={handleClose}
            style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#475569', padding: '0.25rem' }}
            onMouseEnter={e => e.currentTarget.style.color = '#E2E8F0'}
            onMouseLeave={e => e.currentTarget.style.color = '#475569'}
          >
            <X style={{ width: 18, height: 18 }} />
          </button>
        </div>

        {/* Body */}
        <div style={bodyStyle}>
          {/* Success state */}
          {success && (
            <div style={{
              display: 'flex', flexDirection: 'column', alignItems: 'center',
              padding: '2rem 1rem', textAlign: 'center',
            }}>
              <CheckCircle style={{ width: 40, height: 40, color: '#10B981', marginBottom: '1rem' }} />
              <div style={{ fontSize: '0.9rem', color: '#E2E8F0', fontWeight: 600, marginBottom: '0.5rem' }}>
                Submitted successfully
              </div>
              <div style={{ fontSize: '0.75rem', color: '#94A3B8', marginBottom: '1rem' }}>
                Issue #{success.id} created in GitLab
              </div>
              {success.url && (
                <a
                  href={success.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  style={{
                    fontSize: '0.72rem', color: '#0EA5E9',
                    fontFamily: "'JetBrains Mono', monospace",
                    textDecoration: 'none',
                  }}
                  onMouseEnter={e => e.currentTarget.style.textDecoration = 'underline'}
                  onMouseLeave={e => e.currentTarget.style.textDecoration = 'none'}
                >
                  View in GitLab
                </a>
              )}
              <button
                onClick={handleClose}
                style={{
                  ...btnStyle,
                  marginTop: '1.5rem',
                  background: 'rgba(14,165,233,0.15)',
                  color: '#38BDF8',
                }}
                onMouseEnter={e => e.currentTarget.style.background = 'rgba(14,165,233,0.25)'}
                onMouseLeave={e => e.currentTarget.style.background = 'rgba(14,165,233,0.15)'}
              >
                Close
              </button>
            </div>
          )}

          {/* Form */}
          {!success && (
            <form onSubmit={handleSubmit}>
              <TypeSelector value={type} onChange={setType} />

              {/* Title */}
              <div style={{ marginBottom: '1rem' }}>
                <label style={labelStyle}>Title *</label>
                <input
                  type="text"
                  value={title}
                  onChange={e => setTitle(e.target.value)}
                  placeholder={type === 'bug' ? 'Brief description of the issue' : 'What would you like to see?'}
                  style={inputStyle}
                  onFocus={e => e.target.style.borderColor = `${typeColor}80`}
                  onBlur={e => e.target.style.borderColor = 'rgba(14,165,233,0.2)'}
                  autoFocus
                />
              </div>

              {/* Description */}
              <div style={{ marginBottom: '1rem' }}>
                <label style={labelStyle}>
                  {type === 'bug' ? 'Steps to Reproduce / Details *' : 'Description *'}
                </label>
                <textarea
                  value={description}
                  onChange={e => setDescription(e.target.value)}
                  placeholder={type === 'bug'
                    ? '1. Go to...\n2. Click on...\n3. Expected vs actual behavior'
                    : 'Describe the feature, the problem it solves, and any alternatives you considered'
                  }
                  style={textareaStyle}
                  onFocus={e => e.target.style.borderColor = `${typeColor}80`}
                  onBlur={e => e.target.style.borderColor = 'rgba(14,165,233,0.2)'}
                />
              </div>

              {/* Screenshots */}
              <div style={{ marginBottom: '1rem' }}>
                <label style={labelStyle}>Screenshots (optional, max 3)</label>
                <input
                  ref={fileInputRef}
                  type="file"
                  accept={ACCEPTED_TYPES}
                  multiple
                  onChange={handleFileChange}
                  style={{ display: 'none' }}
                />
                <button
                  type="button"
                  onClick={() => fileInputRef.current?.click()}
                  disabled={screenshots.length >= MAX_FILES}
                  style={{
                    ...btnStyle,
                    background: 'rgba(14,165,233,0.06)',
                    border: '1px solid rgba(14,165,233,0.2)',
                    color: screenshots.length >= MAX_FILES ? '#475569' : '#94A3B8',
                    cursor: screenshots.length >= MAX_FILES ? 'not-allowed' : 'pointer',
                    padding: '0.5rem 0.75rem',
                    fontSize: '0.72rem',
                  }}
                >
                  <Image style={{ width: 14, height: 14 }} />
                  {screenshots.length >= MAX_FILES ? 'Max reached' : 'Attach images'}
                </button>
                <span style={{
                  fontSize: '0.65rem', color: '#475569', marginLeft: '0.5rem',
                  fontFamily: "'JetBrains Mono', monospace",
                }}>
                  PNG, JPG, GIF, WebP — 5MB each
                </span>
                <ScreenshotPreviews files={screenshots} onRemove={handleRemoveScreenshot} />
              </div>

              {/* Current page indicator */}
              {currentPage && (
                <div style={{
                  fontSize: '0.68rem', color: '#475569',
                  fontFamily: "'JetBrains Mono', monospace",
                  marginBottom: '1rem',
                }}>
                  Page context: <span style={{ color: '#94A3B8' }}>{currentPage}</span>
                </div>
              )}

              {/* Error */}
              {error && (
                <div style={{
                  display: 'flex', gap: '0.4rem', alignItems: 'center',
                  color: '#F87171', fontSize: '0.75rem', marginBottom: '1rem',
                  fontFamily: "'JetBrains Mono', monospace",
                }}>
                  <AlertCircle style={{ width: 14, height: 14, flexShrink: 0 }} />
                  {error}
                </div>
              )}

              {/* Submit */}
              <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end' }}>
                <button
                  type="button"
                  onClick={handleClose}
                  style={{
                    ...btnStyle,
                    background: 'transparent',
                    border: '1px solid rgba(255,255,255,0.1)',
                    color: '#94A3B8',
                  }}
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={submitting}
                  style={{
                    ...btnStyle,
                    background: `${typeColor}20`,
                    border: `1px solid ${typeColor}`,
                    color: typeColor,
                    opacity: submitting ? 0.6 : 1,
                  }}
                  onMouseEnter={e => { if (!submitting) e.currentTarget.style.background = `${typeColor}35`; }}
                  onMouseLeave={e => e.currentTarget.style.background = `${typeColor}20`}
                >
                  {submitting
                    ? <Loader style={{ width: 14, height: 14, animation: 'spin 1s linear infinite' }} />
                    : <Send style={{ width: 14, height: 14 }} />
                  }
                  Submit
                </button>
              </div>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}
