'use client';

import { useState, useRef, useCallback, useEffect } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { storage, db } from '@/lib/firebase';
import { useAuth } from '@/components/auth-provider';
import { ref, uploadString, getDownloadURL } from 'firebase/storage';
import { collection, addDoc, serverTimestamp } from 'firebase/firestore';
import { Camera, X, RotateCcw, Flashlight, FlashlightOff, Check, Image as ImageIcon } from 'lucide-react';
import { toast } from '@/hooks/use-toast';
import { useLanguage } from '@/hooks/use-language';
import { t } from '@/lib/i18n';

export default function CameraContent() {
  const router = useRouter();
  const { lang } = useLanguage();
  const searchParams = useSearchParams();
  const eventId = searchParams.get('event') || '';
  const { user } = useAuth();
  const videoRef = useRef<HTMLVideoElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [stream, setStream] = useState<MediaStream | null>(null);
  const [photo, setPhoto] = useState<string | null>(null);
  const [flash, setFlash] = useState(false);
  const [facingMode, setFacingMode] = useState<'user' | 'environment'>('environment');
  const [remainingShots, setRemainingShots] = useState(10);
  const [uploading, setUploading] = useState(false);

  const startCamera = useCallback(async () => {
    try {
      const mediaStream = await navigator.mediaDevices.getUserMedia({
        video: { facingMode },
        audio: false,
      });
      setStream(mediaStream);
      if (videoRef.current) {
        videoRef.current.srcObject = mediaStream;
      }
    } catch (err) {
      toast({ title: t(lang, 'cameraAccessDenied'), variant: 'destructive' });
    }
  }, [facingMode]);

  const stopCamera = useCallback(() => {
    if (stream) {
      stream.getTracks().forEach((track) => track.stop());
      setStream(null);
    }
  }, [stream]);

  useEffect(() => {
    startCamera();
    return () => stopCamera();
  }, [startCamera, stopCamera]);

  const takePhoto = () => {
    if (!videoRef.current || !canvasRef.current || remainingShots <= 0) return;
    const video = videoRef.current;
    const canvas = canvasRef.current;
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;
    if (flash) {
      ctx.fillStyle = 'white';
      ctx.fillRect(0, 0, canvas.width, canvas.height);
    }
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
    ctx.strokeStyle = 'rgba(255,255,255,0.1)';
    ctx.lineWidth = 20;
    ctx.strokeRect(0, 0, canvas.width, canvas.height);
    const dataUrl = canvas.toDataURL('image/jpeg', 0.9);
    setPhoto(dataUrl);
    setRemainingShots((prev) => prev - 1);
  };

  const retake = () => {
    setPhoto(null);
    setRemainingShots((prev) => prev + 1);
  };

  const uploadPhoto = async () => {
    if (!photo || !eventId || !user) return;
    setUploading(true);
    try {
      const photoId = `${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
      const storageRef = ref(storage, `events/${eventId}/photos/${photoId}.jpg`);
      await uploadString(storageRef, photo, 'data_url');
      const downloadUrl = await getDownloadURL(storageRef);
      await addDoc(collection(db, 'events', eventId, 'photos'), {
        url: downloadUrl,
        storagePath: `events/${eventId}/photos/${photoId}.jpg`,
        uploadedBy: user.uid,
        guestName: user.displayName || 'Guest',
        eventId: eventId,
        isApproved: false,
        approvalStatus: 'pending',
        likes: 0,
        comments: 0,
        aiAnalyzed: false,
        createdAt: serverTimestamp(),
      });
      toast({ title: t(lang, 'photoUploaded'), variant: 'success' });
      router.push(`/event/${eventId}`);
    } catch (error: any) {
      console.error('Upload error:', error);
      toast({ title: error.message || t(lang, 'uploadFailed'), variant: 'destructive' });
    } finally {
      setUploading(false);
    }
  };

  const toggleFacingMode = () => {
    stopCamera();
    setFacingMode((prev) => (prev === 'user' ? 'environment' : 'user'));
  };

  if (!eventId) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-black">
        <div className="text-center">
          <Camera className="h-12 w-12 text-zinc-600 mx-auto mb-4" />
          <p className="text-zinc-400 mb-4">{t(lang, 'noEventSelected')}</p>
          <button onClick={() => router.push('/dashboard')} className="h-10 px-6 rounded-xl bg-gradient-to-r from-indigo-500 to-purple-600 text-white text-sm font-medium hover:from-indigo-600 hover:to-purple-700 transition-all">
            {t(lang, 'goToDashboard')}
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="fixed inset-0 bg-black z-50 flex flex-col">
      <div className="absolute top-0 left-0 right-0 z-10 flex items-center justify-between p-4">
        <button onClick={() => router.back()} className="h-10 w-10 rounded-full bg-black/50 backdrop-blur-sm flex items-center justify-center text-white hover:bg-black/70 transition-colors">
          <X className="h-5 w-5" />
        </button>
        <div className="px-3 py-1.5 rounded-full bg-black/50 backdrop-blur-sm text-xs text-white font-mono">
          {remainingShots} {t(lang, 'shotsLeft')}
        </div>
        <button onClick={toggleFacingMode} className="h-10 w-10 rounded-full bg-black/50 backdrop-blur-sm flex items-center justify-center text-white hover:bg-black/70 transition-colors">
          <RotateCcw className="h-5 w-5" />
        </button>
      </div>

      <div className="flex-1 relative">
        {photo ? (
          <img src={photo} alt="Captured" className="w-full h-full object-cover" />
        ) : (
          <>
            <video ref={videoRef} autoPlay playsInline muted className="w-full h-full object-cover" />
            <canvas ref={canvasRef} className="hidden" />
            <div className="absolute inset-0 pointer-events-none">
              <div className="absolute top-1/4 left-1/4 right-1/4 bottom-1/4 border border-white/20 rounded-lg" />
              <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-4 h-4 border border-white/40 rounded-full" />
            </div>
          </>
        )}
      </div>

      <div className="absolute bottom-0 left-0 right-0 p-6 pb-10 bg-gradient-to-t from-black/80 to-transparent">
        {photo ? (
          <div className="flex items-center justify-between max-w-sm mx-auto">
            <button onClick={retake} className="flex flex-col items-center gap-1 text-white/70 hover:text-white transition-colors">
              <RotateCcw className="h-6 w-6" />
              <span className="text-xs">{t(lang, 'retake')}</span>
            </button>
            <button onClick={uploadPhoto} disabled={uploading} className="h-16 w-16 rounded-full bg-white flex items-center justify-center hover:bg-zinc-200 transition-colors disabled:opacity-50">
              {uploading ? (
                <div className="h-6 w-6 border-2 border-black border-t-transparent rounded-full animate-spin" />
              ) : (
                <Check className="h-7 w-7 text-black" />
              )}
            </button>
            <button onClick={() => router.push(`/event/${eventId}`)} className="flex flex-col items-center gap-1 text-white/70 hover:text-white transition-colors">
              <ImageIcon className="h-6 w-6" />
              <span className="text-xs">{t(lang, 'gallery')}</span>
            </button>
          </div>
        ) : (
          <div className="flex items-center justify-between max-w-sm mx-auto">
            <button onClick={() => setFlash(!flash)} className={`flex flex-col items-center gap-1 transition-colors ${flash ? 'text-yellow-400' : 'text-white/70 hover:text-white'}`}>
              {flash ? <Flashlight className="h-6 w-6" /> : <FlashlightOff className="h-6 w-6" />}
              <span className="text-xs">{t(lang, 'flash')}</span>
            </button>
            <button onClick={takePhoto} disabled={remainingShots <= 0} className="h-20 w-20 rounded-full border-4 border-white/80 flex items-center justify-center hover:scale-105 transition-transform disabled:opacity-30 disabled:hover:scale-100">
              <div className="h-16 w-16 rounded-full bg-white" />
            </button>
            <button onClick={() => router.push(`/event/${eventId}`)} className="flex flex-col items-center gap-1 text-white/70 hover:text-white transition-colors">
              <ImageIcon className="h-6 w-6" />
              <span className="text-xs">{t(lang, 'gallery')}</span>
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
