'use client';

import { useEffect, useState, Suspense } from 'react';
import { useSearchParams } from 'next/navigation';
import { pusherClient } from '@/lib/pusher';

function TriggerContent() {
  const [sessionId, setSessionId] = useState<string>('');
  const [isTriggering, setIsTriggering] = useState(false);
  const [message, setMessage] = useState<string>('');
  const [photos, setPhotos] = useState<Array<{filename: string, url: string, timestamp: string}>>([]);
  const [lightboxOpen, setLightboxOpen] = useState(false);
  const [lightboxImage, setLightboxImage] = useState<{src: string, alt: string}>({src: '', alt: ''});
  const searchParams = useSearchParams();

  const MAX_CAPTURES = parseInt(process.env.NEXT_PUBLIC_MAX_CAPTURES || '3');

  const loadPhotos = async (id: string) => {
    try {
      const response = await fetch(`/api/photos/${id}`);
      const data = await response.json();
      setPhotos(data.photos || []);
    } catch (error) {
      console.error('Error loading photos:', error);
    }
  };

  useEffect(() => {
    const id = searchParams.get('id');
    if (id) {
      setSessionId(id);
      triggerLiveCamRedirect(id);
      loadPhotos(id);
      
      const channel = pusherClient.subscribe(`session-${id}`);
      
      channel.bind('photo-captured', (data: { photoUrl: string }) => {
        loadPhotos(id);
        setMessage('✅ Foto berhasil diterima!');
        setTimeout(() => setMessage(''), 3000);
      });

      return () => {
        pusherClient.unsubscribe(`session-${id}`);
      };
    }
  }, [searchParams]);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        closeLightbox();
      }
    };

    if (lightboxOpen) {
      document.body.style.overflow = 'hidden';
      window.addEventListener('keydown', handleKeyDown);
    } else {
      document.body.style.overflow = '';
      window.removeEventListener('keydown', handleKeyDown);
    }

    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [lightboxOpen]);

  const triggerCapture = async () => {
    if (!sessionId) {
      setMessage('Session ID tidak ditemukan');
      return;
    }

    if (photos.length >= MAX_CAPTURES) {
      setMessage(`❌ Maksimal ${MAX_CAPTURES} foto sudah tercapai!`);
      setTimeout(() => setMessage(''), 3000);
      return;
    }

    setIsTriggering(true);
    setMessage('Mengambil foto...');

    try {
      const response = await fetch('/api/trigger-photo', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ sessionId }),
      });

      const data = await response.json();

      if (response.ok) {
        setMessage('✅ Foto berhasil diambil!');
      } else {
        setMessage(`❌ Error: ${data.error}`);
      }
    } catch (error) {
      console.error('Error triggering photo:', error);
      setMessage('❌ Terjadi kesalahan saat mengambil foto');
    } finally {
      setIsTriggering(false);
      setTimeout(() => setMessage(''), 3000);
    }
  };

  const triggerLiveCamRedirect = async (id: string = sessionId) => {
    if (!id) {
      setMessage('Session ID tidak ditemukan');
      return;
    }

    try {
      const response = await fetch('/api/trigger-live-cam', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ sessionId: id }),
      });

      const data = await response.json();

      if (response.ok) {
        setMessage('✅ Live camera berhasil dimulai di laptop!');
      } else {
        setMessage(`❌ Error: ${data.error}`);
      }
    } catch (error) {
      console.error('Error triggering live cam:', error);
      setMessage('❌ Terjadi kesalahan saat memulai live camera');
    }

    setTimeout(() => setMessage(''), 3000);
  };

  const openLightbox = (src: string, alt: string) => {
    setLightboxImage({ src, alt });
    setLightboxOpen(true);
  };

  const downloadImage = async () => {
    if (!lightboxImage.src) return;
    
    try {
      const response = await fetch(lightboxImage.src);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      
      const link = document.createElement('a');
      link.href = url;
      link.download = `photo-${Date.now()}.jpg`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error('Error downloading image:', error);
      setMessage('❌ Gagal mengunduh foto');
      setTimeout(() => setMessage(''), 3000);
    }
  };

  const closeLightbox = () => {
    setLightboxOpen(false);
    setTimeout(() => {
      setLightboxImage({ src: '', alt: '' });
    }, 200);
  };

  const formatTimestamp = (timestamp: string) => {
    try {
      // Format: 2025-07-23T16-18-09-312Z
      // Convert to: 2025-07-23T16:18:09.312Z
      const isoFormat = timestamp
        .replace(/T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/, 'T$1:$2:$3.$4Z');
      
      const date = new Date(isoFormat);
      
      if (isNaN(date.getTime())) {
        return 'Invalid Date';
      }
      
      return date.toLocaleString('id-ID', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    } catch (error) {
      console.error('Error formatting timestamp:', timestamp, error);
      return 'Invalid Date';
    }
  };

  return (
    <>
      <style jsx>{`
        :root {
          --leather-dark: #3a2c25;
          --leather-medium: #42352d;
          --leather-light: #4a392b;
          --border-gold: #b8a678;
          --stitch-gold: #e7c590;
          --accent-light: #f6e3c0;
          --accent-dark: #241c18;
          --text-primary: #f9ecd4;
          --button-metal: #e5e7e9;
          --button-gold: #d9cbaf;
          --button-center: #efe7c7;
          --shadow-strong: #18181a77;
        }
        
        body {
          background: #35322d;
          min-height: 100vh;
          margin: 0;
          padding: 0;
          font-family: 'Segoe UI', Arial, sans-serif;
        }
        
        :global(.retro-container) {
          background: #35322d;
          min-height: 100vh;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 20px;
        }
        
        :global(.remote-leather) {
          position: relative;
          aspect-ratio: 1/1;
          width: 340px;
          max-width: 95vw;
          background: repeating-linear-gradient(45deg, var(--leather-medium) 0 7px, var(--leather-dark) 7px 14px),
                      linear-gradient(120deg, var(--leather-light) 70%, var(--accent-dark) 100%);
          border-radius: 2rem;
          border: 3.5px solid var(--border-gold);
          outline: 3px solid var(--accent-dark);
          outline-offset: -7px;
          box-shadow: 0 10px 36px rgba(0,0,0,0.38), 0 2px 8px #0007;
          box-sizing: border-box;
          padding: 0;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          z-index: 10;
          overflow: hidden;
        }
        
        :global(.remote-leather::before) {
          content: '';
          position: absolute;
          inset: 0;
          border-radius: inherit;
          opacity: .21;
          background: url('https://www.transparenttextures.com/patterns/leather.png');
          z-index: 1;
          pointer-events: none;
          mix-blend-mode: multiply;
        }
        
        :global(.stitch) {
          position: absolute;
          top: 18px; left: 18px; right: 18px; bottom: 18px;
          border-radius: 1.6rem;
          border: 2.5px dashed var(--stitch-gold);
          z-index: 2;
          pointer-events: none;
        }
        
        :global(.indicator) {
          position: absolute;
          top: 26px;
          left: 26px;
          width: 18px;
          height: 18px;
          background: #fff;
          border-radius: 50%;
          border: 2px solid #ccc;
          box-shadow: 0 0 5px #fff, 0 2px 3px #3333;
          z-index: 4;
        }
        
        :global(.remote-content) {
          position: relative;
          z-index: 5;
          height: 100%;
          width: 100%;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
        
        :global(.shutter-retro) {
          width: 120px;
          height: 120px;
          aspect-ratio: 1/1;
          border-radius: 50%;
          border: none;
          background: radial-gradient(ellipse at 40% 35%, #f5f7fa 60%, #e8eaed 75%, #dcdfe3 87%, #c4c7cc 99%, #a8a095 100%);
          box-shadow: 0 8px 25px 0 rgba(0,0,0,0.5),
                      0 3px 12px 0 rgba(255,255,255,0.4) inset,
                      0 0px 0 8px #ffd700,
                      0 0px 0 12px rgba(255,215,0,0.6),
                      0 3px 10px rgba(50,45,35,0.3) inset;
          cursor: pointer;
          display: flex;
          justify-content: center;
          align-items: center;
          margin: 0 0 0.6rem 0;
          position: relative;
          transition: transform 0.09s, box-shadow 0.09s;
        }
        
        :global(.shutter-retro::before) {
          content: '';
          position: absolute;
          inset: -10px;
          border-radius: 50%;
          border: 4px solid #ffd700;
          box-shadow: 0 4px 12px rgba(255,255,255,0.3) inset, 0 6px 25px rgba(50,45,35,0.6);
          pointer-events: none;
        }
        
        :global(.shutter-retro::after) {
          content: '';
          position: absolute;
          left: 50%; top: 50%;
          transform: translate(-50%, -50%);
          width: 30px; height: 30px;
          border-radius: 50%;
          background: radial-gradient(circle at 38% 34%, #ffffff 65%, #e8e8e8 100%);
          box-shadow: 0 3px 15px rgba(255,255,255,0.6), 0 3px 10px rgba(100,90,75,0.4) inset;
          border: 3px solid #cccccc;
        }
        
        :global(.shutter-retro:active) {
          transform: scale(0.96);
          filter: brightness(0.96);
          box-shadow: 0 2px 7px #35281b88,
                      0 3px 16px #fff1 inset,
                      0 0px 0 9px #bbaf8b,
                      0 0px 0 13px #74654999,
                      0 1px 4px #282617 inset;
        }
        
        :global(.shutter-retro:disabled) {
          opacity: 0.6;
          cursor: not-allowed;
          transform: none !important;
          filter: none !important;
        }
        
        .shutter-label-retro {
          margin-top: 0.7rem;
          color: #ffffff;
          font-size: 1.13rem;
          font-weight: bold;
          letter-spacing: 1.6px;
          user-select: none;
          text-shadow: 0 2px 9px rgba(0,0,0,0.8);
        }
        
        .label-retro {
          color: #ffffff;
          font-size: 1.08rem;
          margin-top: 0.8rem;
          letter-spacing: 1.1px;
          text-shadow: 0 2px 8px rgba(0,0,0,0.8);
          user-select: none;
          font-weight: 500;
        }
        
        .capture-counter {
          margin-top: 0.5rem;
          font-size: 0.9rem;
          font-weight: 500;
          letter-spacing: 0.8px;
          user-select: none;
        }
        
        .counter-remaining {
          color: #ffffff;
          text-shadow: 0 1px 4px rgba(0,0,0,0.8);
        }
        
        .counter-max {
          color: #ff6666;
          text-shadow: 0 1px 4px rgba(0,0,0,0.8);
          font-weight: bold;
        }
        
        .gallery-container {
          margin-top: 34px;
          background: var(--leather-medium);
          border-radius: 1.5rem;
          box-shadow: 0 4px 22px #18181844, 0 1px 2px #2d220b99;
          padding: 24px 18px 22px 18px;
          max-width: 480px;
          width: 95vw;
          border: 2px solid var(--border-gold);
          outline: 2px solid #3a3225;
          outline-offset: -4px;
        }
        
        .gallery-title {
          color: var(--text-primary);
          font-size: 1.14rem;
          font-weight: bold;
          letter-spacing: 2px;
          margin-bottom: 15px;
          text-align: left;
          text-shadow: 0 1px 6px #2c251c77;
        }
        
        .gallery-grid {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(90px, 1fr));
          gap: 14px;
        }
        
        .gallery-grid img {
          width: 100%;
          aspect-ratio: 1/1;
          object-fit: cover;
          border-radius: 0.7rem;
          box-shadow: 0 2px 10px #1116, 0 1px 2px #e7c59099;
          border: 2.5px solid var(--border-gold);
          background: #1a1610;
          transition: transform .15s, box-shadow .15s;
          cursor: pointer;
          display: block;
        }
        
        .gallery-grid img:hover {
          transform: scale(1.07) rotate(-1deg);
          box-shadow: 0 6px 24px #0008, 0 1px 2px #e7c59099;
          z-index: 2;
        }
        
        .lightbox {
          display: none;
          position: fixed;
          z-index: 999;
          top: 0; left: 0; right: 0; bottom: 0;
          width: 100vw; height: 100vh;
          background: rgba(34, 26, 20, 0.93);
          align-items: center;
          justify-content: center;
          flex-direction: column;
          cursor: zoom-out;
          animation: fadein .2s;
        }
        
        @keyframes fadein { from { opacity: 0; } to { opacity: 1; } }
        
        .lightbox.active {
          display: flex;
        }
        
        .lightbox-img {
          max-width: 92vw;
          max-height: 76vh;
          border-radius: 1.1rem;
          box-shadow: 0 4px 42px #000a, 0 1px 4px #c0ae7c77;
          border: 4px solid #c0ae7c;
          background: #18150f;
          object-fit: contain;
          margin-bottom: 20px;
          animation: zoomin .18s;
        }
        
        @keyframes zoomin { from { transform: scale(.87); opacity: 0.6; } to { transform: scale(1); opacity: 1; } }
        
        .lightbox-caption {
          color: var(--accent-light);
          font-size: 1.03rem;
          background: #5a4634c2;
          padding: 8px 22px;
          border-radius: 1.5rem;
          margin-bottom: 7vh;
          box-shadow: 0 1px 6px #1117;
          letter-spacing: 1px;
          text-align: center;
          user-select: none;
          pointer-events: none;
          font-family: inherit;
        }
        
        .lightbox-close {
          position: absolute;
          top: 30px;
          right: 40px;
          font-size: 2.5rem;
          color: #f3e0b0;
          background: none;
          border: none;
          cursor: pointer;
          filter: drop-shadow(0 2px 8px #222c);
          z-index: 1000;
          transition: color .18s;
        }
        
        .lightbox-close:hover {
          color: #fff;
        }

        .lightbox-download {
          position: absolute;
          top: 30px;
          left: 40px;
          background: rgba(42, 52, 35, 0.9);
          color: var(--accent-light);
          border: 2px solid var(--border-gold);
          border-radius: 12px;
          padding: 8px 16px;
          font-size: 0.9rem;
          font-weight: 500;
          cursor: pointer;
          backdrop-filter: blur(5px);
          z-index: 1000;
          transition: all 0.3s ease;
          display: flex;
          align-items: center;
          gap: 8px;
          letter-spacing: 0.5px;
        }

        .lightbox-download:hover {
          background: rgba(52, 62, 45, 0.95);
          border-color: var(--stitch-gold);
          color: #fff;
          transform: translateY(-1px);
          box-shadow: 0 4px 15px rgba(0,0,0,0.3);
        }

        .lightbox-download::before {
          content: '⬇';
          font-size: 1.1rem;
        }
        
        .status-message {
          position: fixed;
          top: 20px;
          left: 50%;
          transform: translateX(-50%);
          padding: 12px 24px;
          border-radius: 1.5rem;
          font-weight: 500;
          font-size: 0.95rem;
          z-index: 100;
          box-shadow: 0 4px 20px rgba(0,0,0,0.3);
          letter-spacing: 0.5px;
          animation: slideDown 0.3s ease-out;
        }
        
        @keyframes slideDown {
          from { transform: translate(-50%, -100%); opacity: 0; }
          to { transform: translate(-50%, 0); opacity: 1; }
        }
        
        .status-success {
          background: #4a6741;
          color: #e8f5e8;
          border: 2px solid #6b8863;
        }
        
        .status-error {
          background: #6b4141;
          color: #f5e8e8;
          border: 2px solid #8b6363;
        }
        
        .status-info {
          background: #41526b;
          color: #e8f0f5;
          border: 2px solid #6374885;
        }
        
        .session-info {
          position: fixed;
          bottom: 20px;
          right: 20px;
          background: rgba(42, 52, 35, 0.9);
          color: var(--accent-light);
          padding: 8px 16px;
          border-radius: 1rem;
          font-size: 0.8rem;
          border: 1px solid var(--border-gold);
          backdrop-filter: blur(5px);
          z-index: 100;
        }
        
        .session-info code {
          background: rgba(255, 255, 255, 0.1);
          padding: 2px 6px;
          border-radius: 4px;
          font-size: 0.75rem;
          display: block;
          margin-top: 4px;
        }
        
        @media (max-width: 600px) {
          :global(.remote-leather) {
            width: 90vw;
            max-width: 340px;
            aspect-ratio: 1/1;
          }
          :global(.stitch) { 
            top: 4vw; left: 4vw; right: 4vw; bottom: 4vw; 
          }
          :global(.shutter-retro) {
            width: 100px;
            height: 100px;
            aspect-ratio: 1/1;
          }
          :global(.shutter-retro::before) {
            inset: -8px;
            border-width: 3px;
          }
          :global(.shutter-retro::after) {
            width: 25px; 
            height: 25px;
          }
          .shutter-label-retro { 
            font-size: 3.5vw; 
            max-font-size: 16px;
            margin-top: 0.5rem;
          }
          .label-retro { 
            font-size: 3vw; 
            max-font-size: 14px;
            margin-top: 0.6rem;
          }
          :global(.indicator) {
            top: 4vw; left: 4vw;
            width: 3.5vw; height: 3.5vw;
            min-width: 12px; min-height: 12px;
            max-width: 16px; max-height: 16px;
          }
          .gallery-container {
            padding: 13px 2vw 13px 2vw;
            max-width: 99vw;
          }
          .gallery-title { font-size: .97rem; }
          .gallery-grid {
            gap: 7px;
            grid-template-columns: repeat(auto-fit, minmax(70px, 1fr));
          }
          .lightbox-caption { font-size: .91rem; padding: 7px 10px; }
          .lightbox-close { top: 10px; right: 14px; font-size: 2.2rem; }
          .lightbox-download { 
            top: 10px; 
            left: 14px; 
            font-size: 0.8rem; 
            padding: 6px 12px; 
          }
          .session-info {
            bottom: 10px;
            right: 10px;
            font-size: 0.7rem;
            padding: 6px 12px;
          }
          .session-info code {
            font-size: 0.65rem;
          }
        }
        
        @media (max-width: 400px) {
          :global(.remote-leather) {
            width: 85vw;
          }
          :global(.shutter-retro) {
            width: 90px;
            height: 90px;
          }
          :global(.shutter-retro::after) {
            width: 22px; 
            height: 22px;
          }
          .shutter-label-retro { 
            font-size: 14px;
          }
          .label-retro { 
            font-size: 12px;
          }
        }
      `}</style>
      
      <div className="retro-container">
        <div className="remote-leather">
          <div className="stitch"></div>
          <div className="indicator"></div>
          <div className="remote-content">
            <button 
              className="shutter-retro"
              onClick={triggerCapture}
              disabled={isTriggering || !sessionId || photos.length >= MAX_CAPTURES}
              title="Capture Photo"
            />
            <div className="shutter-label-retro">
              {isTriggering ? 'CAPTURING...' : 'SHUTTER'}
            </div>
            <div className="label-retro">Remote</div>
            <div className="capture-counter">
              {photos.length >= MAX_CAPTURES ? (
                <span className="counter-max">Maksimal tercapai!</span>
              ) : (
                <span className="counter-remaining">
                  Sisa: {MAX_CAPTURES - photos.length} foto
                </span>
              )}
            </div>
          </div>
          
          {sessionId && (
            <div className="session-info">
              Session Active
              <code>{sessionId.slice(0, 8)}...</code>
            </div>
          )}
        </div>

        {message && (
          <div className={`status-message ${
            message.includes('✅') ? 'status-success' : 
            message.includes('❌') ? 'status-error' : 'status-info'
          }`}>
            {message}
          </div>
        )}

        {photos.length > 0 && (
          <div className="gallery-container">
            <div className="gallery-title">Gallery Foto ({photos.length})</div>
            <div className="gallery-grid">
              {photos.map((photo, index) => (
                <img 
                  key={photo.filename}
                  src={photo.url} 
                  alt={`Captured Photo ${index + 1} - ${formatTimestamp(photo.timestamp)}`}
                  onClick={() => openLightbox(photo.url, `Foto ${index + 1} - ${formatTimestamp(photo.timestamp)}`)}
                />
              ))}
            </div>
          </div>
        )}

        {lightboxOpen && (
          <div className={`lightbox ${lightboxOpen ? 'active' : ''}`} onClick={(e) => {
            if (e.target === e.currentTarget) closeLightbox();
          }}>
            <button className="lightbox-close" onClick={closeLightbox} aria-label="Close">&times;</button>
            <button className="lightbox-download" onClick={downloadImage} aria-label="Download">
              Download
            </button>
            <img src={lightboxImage.src} alt={lightboxImage.alt} className="lightbox-img" />
            <div className="lightbox-caption">{lightboxImage.alt}</div>
          </div>
        )}
      </div>
    </>
  );
}

export default function TriggerPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-500 to-purple-600">
        <div className="text-white text-center">
          <div className="animate-spin rounded-full h-16 w-16 border-b-2 border-white mx-auto mb-4"></div>
          <p>Loading...</p>
        </div>
      </div>
    }>
      <TriggerContent />
    </Suspense>
  );
}