import React, { useState, useEffect, StrictMode, useRef } from 'react';
import { createRoot } from 'react-dom/client';
import { Twitter, Instagram, Send, Trash2, X, Image as ImageIcon } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import './index.css';

// --- Types ---
interface Message {
  id: string;
  text?: string;
  imageUrl?: string;
  sender: 'me' | 'them';
  timestamp: Date;
}

// --- Components ---

const Header = () => (
  <header className="fixed top-0 left-0 right-0 bg-white/90 backdrop-blur-sm z-50 border-b border-gray-100">
    <div className="max-w-5xl mx-auto px-6 py-6 flex flex-col md:flex-row justify-between items-center gap-4">
      <h1 className="text-2xl font-serif tracking-widest uppercase text-gray-900">Lou Pantail</h1>
      <nav>
        <ul className="flex flex-wrap justify-center gap-6 text-sm tracking-wide text-gray-600 uppercase font-light">
          <li><a href="#" className="hover:text-black transition-colors">Accueil</a></li>
          <li><a href="#" className="hover:text-black transition-colors">Carte Restaurant</a></li>
          <li><a href="#" className="hover:text-black transition-colors">Carte Livraison</a></li>
          <li><a href="#" className="hover:text-black transition-colors">Photos / Presse</a></li>
          <li><a href="#" className="text-black font-medium border-b border-black pb-1">Contact</a></li>
        </ul>
      </nav>
    </div>
  </header>
);

const MainContent = () => (
  <main className="flex-grow flex flex-col items-center justify-center pt-32 pb-20 px-6 text-center">
    <div className="max-w-2xl space-y-8">
      <h2 className="text-4xl md:text-5xl font-serif text-gray-900 mb-12">Contact</h2>
      
      <div className="space-y-2 font-light text-lg tracking-wide text-gray-700">
        <p className="uppercase font-medium text-gray-900">Lou Pantail</p>
        <p>ouvert du mardi au dimanche</p>
        <p>(12:00-14h30 / 19:30-23:30)</p>
      </div>

      <div className="pt-8">
        <a 
          href="mailto:contact@loupantail.com" 
          className="text-xl font-serif italic text-gray-900 border-b border-gray-300 hover:border-black transition-colors pb-1"
        >
          contact@loupantail.com
        </a>
      </div>
    </div>
  </main>
);

const Footer = ({ onTwitterClick }: { onTwitterClick: () => void }) => (
  <footer className="w-full py-12 px-6 border-t border-gray-100 bg-white">
    <div className="max-w-5xl mx-auto flex justify-between items-end">
      <div className="text-xs text-gray-400 font-light tracking-wider">
        © {new Date().getFullYear()} LOU PANTAIL
      </div>
      <div className="flex gap-6">
        <a href="#" className="text-gray-400 hover:text-black transition-colors">
          <Instagram size={20} strokeWidth={1.5} />
        </a>
        <button 
          onClick={onTwitterClick}
          className="text-gray-400 hover:text-[#1DA1F2] transition-colors focus:outline-none"
          aria-label="Open Chat"
        >
          <Twitter size={20} strokeWidth={1.5} />
        </button>
      </div>
    </div>
  </footer>
);

const ChatWidget = ({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) => {
  const [messages, setMessages] = useState<Message[]>(() => {
    if (typeof window !== 'undefined') {
      const saved = localStorage.getItem('chat_messages');
      if (saved) {
        try {
          return JSON.parse(saved).map((m: any) => ({
            ...m,
            timestamp: new Date(m.timestamp)
          }));
        } catch (e) {
          console.error("Failed to parse messages", e);
        }
      }
    }
    return [{ id: '1', text: 'Bonjour ! Comment pouvons-nous vous aider ?', sender: 'them', timestamp: new Date() }];
  });
  const [inputValue, setInputValue] = useState('');
  const [selectedImage, setSelectedImage] = useState<string | null>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  useEffect(() => {
    try {
      localStorage.setItem('chat_messages', JSON.stringify(messages));
    } catch (e) {
      console.error("Failed to save messages", e);
    }
  }, [messages]);

  const handleSend = (e?: React.FormEvent) => {
    e?.preventDefault();
    if (!inputValue.trim()) return;

    const newMessage: Message = {
      id: Date.now().toString(),
      text: inputValue,
      sender: 'me',
      timestamp: new Date()
    };

    setMessages(prev => [...prev, newMessage]);
    setInputValue('');
  };

  const [isUploading, setIsUploading] = useState(false);

  const [isBackendHealthy, setIsBackendHealthy] = useState(true);

  useEffect(() => {
    if (window.location.protocol === 'file:') {
      setIsBackendHealthy(false);
      return;
    }
    fetch('/api/health')
      .then(res => {
        if (!res.ok) throw new Error('Backend unhealthy');
        setIsBackendHealthy(true);
      })
      .catch(() => setIsBackendHealthy(false));
  }, []);

  const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!isBackendHealthy) {
      alert("Backend server is unreachable. Image uploads require a running backend server.");
      return;
    }
    const file = e.target.files?.[0];
    if (!file) return;

    setIsUploading(true);
    const formData = new FormData();
    formData.append('image', file);

    try {
      const response = await fetch('/api/upload', {
        method: 'POST',
        body: formData,
      });

      if (response.ok) {
        const data = await response.json();
        const newMessage: Message = {
          id: Date.now().toString(),
          imageUrl: `/uploads/${data.filename}`,
          sender: 'me',
          timestamp: new Date()
        };
        setMessages(prev => [...prev, newMessage]);
      } else {
        console.error('Failed to upload image');
        alert('Failed to upload image. Please try again.');
      }
    } catch (error) {
      console.error('Error uploading image:', error);
      alert('Error uploading image. Please check your connection.');
    } finally {
      setIsUploading(false);
    }
    
    // Reset file input
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  const handleDelete = async (id: string, imageUrl?: string) => {
    // Optimistically update UI
    setMessages(prev => prev.filter(m => m.id !== id));

    // If it's an image message, delete from server
    if (imageUrl) {
      const filename = imageUrl.split('/').pop();
      if (filename) {
        try {
          await fetch(`/api/images/${filename}`, {
            method: 'DELETE',
          });
        } catch (error) {
          console.error('Error deleting image:', error);
        }
      }
    }
  };

  return (
    <AnimatePresence>
      {isOpen && (
        <motion.div
          initial={{ opacity: 0, y: 20, scale: 0.95 }}
          animate={{ opacity: 1, y: 0, scale: 1 }}
          exit={{ opacity: 0, y: 20, scale: 0.95 }}
          transition={{ duration: 0.2 }}
          className="fixed bottom-24 right-6 w-80 md:w-96 bg-white rounded-2xl shadow-2xl border border-gray-100 overflow-hidden z-50 flex flex-col font-sans"
          style={{ height: '500px', maxHeight: '70vh' }}
        >
          {/* Header */}
          <div className="bg-gray-50/80 backdrop-blur-md px-4 py-3 border-b border-gray-100 flex justify-between items-center sticky top-0 z-10">
            <div className="flex items-center gap-3">
              <div className="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center text-gray-500">
                <span className="font-serif font-bold text-xs">LP</span>
              </div>
              <div className="flex flex-col">
                <span className="font-medium text-sm text-gray-900">Lou Pantail</span>
                <span className="text-[10px] text-gray-500">Répond habituellement en 1h</span>
              </div>
            </div>
            <button 
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600 transition-colors p-1.5 rounded-full hover:bg-gray-100"
            >
              <X size={18} />
            </button>
          </div>

          {/* Messages */}
          <div className="flex-grow overflow-y-auto p-4 space-y-4 bg-white scroll-smooth">
            {messages.length === 0 && (
              <div className="text-center text-gray-400 text-xs mt-10">
                Aucun message. Commencez la discussion !
              </div>
            )}
            {messages.map((msg) => (
              <div 
                key={msg.id} 
                className={`flex flex-col ${msg.sender === 'me' ? 'items-end' : 'items-start'} group`}
              >
                <div className={`flex items-end gap-2 max-w-[85%] ${msg.sender === 'me' ? 'flex-row-reverse' : 'flex-row'} relative group`}>
                  <div 
                    className={`px-4 py-2.5 text-sm relative shadow-sm ${
                      msg.sender === 'me' 
                        ? 'bg-blue-600 text-white rounded-2xl rounded-br-sm' 
                        : 'bg-gray-100 text-gray-800 rounded-2xl rounded-bl-sm'
                    }`}
                  >
                    {msg.imageUrl ? (
                      <img 
                        src={msg.imageUrl} 
                        alt="Uploaded" 
                        className="max-w-full rounded-lg cursor-pointer hover:opacity-90 transition-opacity" 
                        onClick={() => setSelectedImage(msg.imageUrl || null)}
                      />
                    ) : (
                      msg.text
                    )}
                  </div>
                  
                  {/* Delete Action */}
                  <button
                    onClick={() => handleDelete(msg.id, msg.imageUrl)}
                    className={`absolute -top-2 ${msg.sender === 'me' ? '-left-2' : '-right-2'} 
                      opacity-0 group-hover:opacity-100 transition-opacity 
                      bg-white text-gray-400 hover:text-red-500 
                      p-1 rounded-full shadow-sm border border-gray-100 z-10`}
                    title="Effacer"
                  >
                    <Trash2 size={12} />
                  </button>
                </div>
                <span className="text-[10px] text-gray-300 mt-1 px-1">
                  {msg.timestamp.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                </span>
              </div>
            ))}
            {isUploading && (
              <div className="flex justify-end">
                <div className="bg-gray-100 rounded-2xl rounded-br-sm px-4 py-3 flex gap-1 items-center">
                  <div className="w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0ms' }} />
                  <div className="w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '150ms' }} />
                  <div className="w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '300ms' }} />
                </div>
              </div>
            )}
            <div ref={messagesEndRef} />
          </div>

          {/* Input */}
          <form onSubmit={handleSend} className="p-3 border-t border-gray-100 bg-white flex gap-2 items-center">
            <input
              type="file"
              accept="image/*"
              className="hidden"
              ref={fileInputRef}
              onChange={handleImageUpload}
            />
            <button
              type="button"
              onClick={() => fileInputRef.current?.click()}
              className="text-gray-400 hover:text-gray-600 p-2 rounded-full hover:bg-gray-100 transition-colors"
            >
              <ImageIcon size={20} />
            </button>
            <input
              type="text"
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              placeholder="Écrivez un message..."
              className="flex-grow bg-gray-100 border-transparent focus:bg-white border focus:border-blue-500 rounded-full px-4 py-2.5 text-sm focus:outline-none transition-all placeholder:text-gray-400"
            />
            <button 
              type="submit"
              disabled={!inputValue.trim()}
              className="bg-blue-600 text-white p-2.5 rounded-full hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors shadow-sm flex-shrink-0"
            >
              <Send size={18} strokeWidth={2} className="ml-0.5" />
            </button>
          </form>
        </motion.div>
      )}
      
      {/* Full Screen Image Modal */}
      {selectedImage && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="fixed inset-0 z-[60] bg-black/90 flex items-center justify-center p-4 backdrop-blur-sm"
          onClick={() => setSelectedImage(null)}
        >
          <button 
            onClick={() => setSelectedImage(null)}
            className="absolute top-4 right-4 text-white/70 hover:text-white transition-colors p-2 rounded-full hover:bg-white/10"
          >
            <X size={32} />
          </button>
          <motion.img
            initial={{ scale: 0.9, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0.9, opacity: 0 }}
            src={selectedImage}
            alt="Full screen"
            className="max-w-full max-h-[90vh] object-contain rounded-lg shadow-2xl"
            onClick={(e) => e.stopPropagation()}
          />
        </motion.div>
      )}
    </AnimatePresence>
  );
};

interface ErrorBoundaryProps {
  children: React.ReactNode;
}

interface ErrorBoundaryState {
  hasError: boolean;
  error: Error | null;
}

class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
  state: ErrorBoundaryState = { hasError: false, error: null };
  props: ErrorBoundaryProps;

  constructor(props: ErrorBoundaryProps) {
    super(props);
    this.props = props;
  }

  static getDerivedStateFromError(error: Error): ErrorBoundaryState {
    return { hasError: true, error };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error("Uncaught error:", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="p-8 text-center">
          <h1 className="text-2xl font-bold text-red-600 mb-4">Something went wrong.</h1>
          <pre className="text-left bg-gray-100 p-4 rounded overflow-auto text-sm">
            {this.state.error?.toString()}
          </pre>
          <button 
            onClick={() => window.location.reload()} 
            className="mt-4 px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
          >
            Reload Page
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}

function App() {
  const [isChatOpen, setIsChatOpen] = useState(false);

  return (
    <div className="min-h-screen flex flex-col bg-white font-sans text-gray-900 selection:bg-gray-100">
      <Header />
      <MainContent />
      <Footer onTwitterClick={() => setIsChatOpen(!isChatOpen)} />
      <ChatWidget isOpen={isChatOpen} onClose={() => setIsChatOpen(false)} />
    </div>
  );
}

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <ErrorBoundary>
      <App />
    </ErrorBoundary>
  </StrictMode>,
);
