'use client';

import React, { useState, useRef, useEffect, useCallback } from 'react';
import { X, RefreshCw, FlipHorizontal, ArrowLeft } from 'lucide-react';
import { FaceAuraAnalysisResult } from '@/lib/aura/faceAnalyzer';
import { CHAKRA_METADATA } from '@/lib/aura/calculator';
import { ChakraType } from '@/lib/aura/types';

interface FaceAuraScannerModalProps {
  isOpen: boolean;
  onClose: () => void;
  onComplete?: (result: FaceAuraAnalysisResult) => void;
}

export const FaceAuraScannerModal: React.FC<FaceAuraScannerModalProps> = ({
  isOpen,
  onClose,
  onComplete,
}) => {
  const [streamActive, setStreamActive] = useState(false);
  const [cameraError, setCameraError] = useState<string | null>(null);
  const [facingMode, setFacingMode] = useState<'user' | 'environment'>('user');
  const [capturedPhoto, setCapturedPhoto] = useState<string | null>(null);
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [result, setResult] = useState<FaceAuraAnalysisResult | null>(null);

  const videoRef = useRef<HTMLVideoElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const streamRef = useRef<MediaStream | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Start device camera
  const startCamera = useCallback(async (facing: 'user' | 'environment' = 'user') => {
    setCameraError(null);
    try {
      if (streamRef.current) {
        streamRef.current.getTracks().forEach((t) => t.stop());
      }

      const stream = await navigator.mediaDevices.getUserMedia({
        video: {
          facingMode: facing,
          width: { ideal: 1280 },
          height: { ideal: 720 },
        },
        audio: false,
      });

      streamRef.current = stream;
      if (videoRef.current) {
        videoRef.current.srcObject = stream;
        videoRef.current.play();
        setStreamActive(true);
      }
    } catch (err: unknown) {
      console.warn('Camera access error:', err);
      setCameraError(
        'Kamera tidak dapat diakses langsung. Anda tetap dapat mengunggah foto selfie dari galeri.'
      );
      setStreamActive(false);
    }
  }, []);

  // Stop device camera tracks
  const stopCamera = useCallback(() => {
    if (streamRef.current) {
      streamRef.current.getTracks().forEach((track) => track.stop());
      streamRef.current = null;
    }
    setStreamActive(false);
  }, []);

  useEffect(() => {
    if (isOpen && !capturedPhoto && !result) {
      startCamera(facingMode);
    }
    return () => {
      stopCamera();
    };
  }, [isOpen, capturedPhoto, result, facingMode, startCamera, stopCamera]);

  // Flip front / rear camera
  const toggleCamera = () => {
    const nextFacing = facingMode === 'user' ? 'environment' : 'user';
    setFacingMode(nextFacing);
    startCamera(nextFacing);
  };

  // Shutter click: snap photo from video feed
  const capturePhoto = () => {
    if (!videoRef.current || !canvasRef.current) return;
    const video = videoRef.current;
    const canvas = canvasRef.current;

    canvas.width = video.videoWidth || 640;
    canvas.height = video.videoHeight || 480;

    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    // If front camera, flip horizontally for natural mirror look
    if (facingMode === 'user') {
      ctx.translate(canvas.width, 0);
      ctx.scale(-1, 1);
    }
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

    const dataUrl = canvas.toDataURL('image/jpeg', 0.88);
    setCapturedPhoto(dataUrl);
    stopCamera();
    runAnalysis(dataUrl);
  };

  // Handle fallback file upload
  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        const dataUrl = reader.result as string;
        setCapturedPhoto(dataUrl);
        stopCamera();
        runAnalysis(dataUrl);
      };
      reader.readAsDataURL(file);
    }
  };

  // Call AI Aura Backend
  const runAnalysis = async (photoData: string) => {
    setIsAnalyzing(true);
    try {
      const res = await fetch('/api/aura/analyze-face', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          imageBase64: photoData.slice(0, 500),
          imageHash: (photoData.length + Date.now()).toString(),
        }),
      });

      const json = await res.json();
      if (json.success && json.data) {
        setResult(json.data);
        onComplete?.(json.data);
      }
    } catch (err) {
      console.error(err);
    } finally {
      setIsAnalyzing(false);
    }
  };

  const handleRetake = () => {
    setCapturedPhoto(null);
    setResult(null);
    setIsAnalyzing(false);
    startCamera(facingMode);
  };

  if (!isOpen) return null;

  const chakrasOrder: ChakraType[] = [
    'crown',
    'third_eye',
    'throat',
    'heart',
    'solar_plexus',
    'sacral',
    'root',
  ];

  return (
    <div className="fixed inset-0 z-50 flex items-start justify-center p-3 sm:p-6 bg-black/90 backdrop-blur-2xl animate-fade-in overflow-y-auto">
      <div className="relative w-full max-w-3xl bg-[#0B0D12] text-white rounded-3xl overflow-hidden shadow-2xl border border-white/10 my-auto flex flex-col">
        {/* Top Minimal Bar */}
        <div className="px-6 py-4 flex items-center justify-between border-b border-white/5">
          <div className="flex items-center gap-3">
            <span className="text-xs uppercase tracking-widest text-[#86868B] font-medium">
              Aura+ Camera
            </span>
          </div>
          <button
            onClick={() => {
              stopCamera();
              onClose();
            }}
            className="w-8 h-8 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition-colors"
          >
            <X className="w-4 h-4" />
          </button>
        </div>

        {/* 1. Live Viewfinder State */}
        {!capturedPhoto && !result && (
          <div className="p-6 sm:p-8 flex flex-col items-center">
            {/* Viewfinder Frame */}
            <div className="relative w-full max-w-md aspect-[4/5] rounded-3xl overflow-hidden bg-black flex items-center justify-center border border-white/10 shadow-2xl">
              {/* Video Element */}
              <video
                ref={videoRef}
                autoPlay
                playsInline
                muted
                className={`w-full h-full object-cover ${
                  facingMode === 'user' ? 'scale-x-[-1]' : ''
                }`}
              />

              {/* Minimal Apple-Style Viewfinder Brackets */}
              <div className="absolute inset-8 pointer-events-none border border-white/20 rounded-2xl flex flex-col justify-between p-4">
                <div className="flex justify-between">
                  <div className="w-4 h-4 border-t-2 border-l-2 border-white/80 rounded-tl" />
                  <div className="w-4 h-4 border-t-2 border-r-2 border-white/80 rounded-tr" />
                </div>
                <div className="flex justify-between">
                  <div className="w-4 h-4 border-b-2 border-l-2 border-white/80 rounded-bl" />
                  <div className="w-4 h-4 border-b-2 border-r-2 border-white/80 rounded-br" />
                </div>
              </div>

              {/* Subtle instruction text */}
              <div className="absolute top-4 inset-x-0 text-center pointer-events-none">
                <span className="text-[11px] font-medium tracking-wide text-white/80 bg-black/40 backdrop-blur-md px-3.5 py-1 rounded-full">
                  Posisikan wajah Anda di dalam bingkai
                </span>
              </div>

              {cameraError && (
                <div className="absolute inset-0 bg-black/90 p-6 flex flex-col items-center justify-center text-center space-y-4">
                  <p className="text-xs text-slate-300 max-w-xs">{cameraError}</p>
                  <button
                    onClick={() => fileInputRef.current?.click()}
                    className="px-5 py-2.5 rounded-full bg-white text-black text-xs font-semibold hover:bg-slate-200 transition-colors"
                  >
                    Pilih Foto dari Galeri
                  </button>
                </div>
              )}
            </div>

            {/* Hidden Canvas for Frame Capture */}
            <canvas ref={canvasRef} className="hidden" />
            <input
              ref={fileInputRef}
              type="file"
              accept="image/*"
              onChange={handleFileUpload}
              className="hidden"
            />

            {/* Shutter & Controls Row */}
            <div className="w-full max-w-md mt-6 flex items-center justify-between px-6">
              <button
                onClick={() => fileInputRef.current?.click()}
                className="text-xs font-medium text-[#86868B] hover:text-white transition-colors"
              >
                Pilih File
              </button>

              {/* Shutter Button (Apple iPhone Camera Style) */}
              <button
                disabled={!streamActive && !cameraError}
                onClick={capturePhoto}
                aria-label="Ambil Foto"
                className="w-18 h-18 rounded-full border-[3px] border-white p-1 hover:scale-105 active:scale-95 transition-transform flex items-center justify-center"
              >
                <div className="w-full h-full rounded-full bg-white transition-all active:bg-white/80" />
              </button>

              <button
                onClick={toggleCamera}
                title="Ganti Kamera Depan/Belakang"
                className="w-10 h-10 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center text-white transition-colors"
              >
                <FlipHorizontal className="w-4 h-4" />
              </button>
            </div>
          </div>
        )}

        {/* 2. Analyzing State */}
        {isAnalyzing && (
          <div className="p-12 sm:p-16 flex flex-col items-center justify-center text-center space-y-6">
            <div className="relative w-44 h-44 rounded-full overflow-hidden border border-white/20 shadow-2xl">
              {capturedPhoto && (
                <img
                  src={capturedPhoto}
                  alt="Captured face"
                  className="w-full h-full object-cover filter brightness-90"
                />
              )}
              {/* Apple-style circular aura pulse */}
              <div className="absolute inset-0 bg-gradient-to-t from-blue-500/30 via-transparent to-transparent animate-pulse" />
            </div>

            <div className="space-y-2">
              <h3 className="text-xl font-medium tracking-tight text-white">
                Membaca Spektrum Aura Wajah...
              </h3>
              <p className="text-xs text-[#86868B]">
                Menyelaraskan vitalitas visual dengan sistem intelijen Aura+.
              </p>
            </div>
          </div>
        )}

        {/* 3. Results State (Apple Health / Clean Editorial Layout) */}
        {!isAnalyzing && result && capturedPhoto && (
          <div className="p-6 sm:p-10 space-y-8 overflow-y-auto max-h-[80vh]">
            {/* Header: Photo + Profile */}
            <div className="flex flex-col sm:flex-row items-center gap-6 pb-6 border-b border-white/10">
              <div className="relative w-24 h-24 rounded-full overflow-hidden shrink-0 border-2 border-white/30 shadow-lg">
                <img
                  src={capturedPhoto}
                  alt="Portrait"
                  className="w-full h-full object-cover"
                />
              </div>

              <div className="text-center sm:text-left space-y-1 flex-1">
                <span className="text-[10px] uppercase tracking-widest text-[#86868B] font-semibold">
                  Aura Profile
                </span>
                <h3 className="text-2xl sm:text-3xl font-bold tracking-tight text-white">
                  {result.auraProfile}
                </h3>
                <p className="text-xs sm:text-sm text-slate-300 leading-relaxed max-w-xl">
                  {result.interpretation.summary}
                </p>
              </div>
            </div>

            {/* Chakra Distribution Bars */}
            <div className="space-y-3">
              <span className="text-[11px] font-semibold tracking-wider uppercase text-[#86868B] block">
                Keseimbangan 7 Cakra
              </span>
              <div className="space-y-2.5">
                {chakrasOrder.map((chKey) => {
                  const meta = CHAKRA_METADATA[chKey];
                  const score = result.scores[chKey];
                  return (
                    <div key={chKey} className="space-y-1">
                      <div className="flex justify-between items-center text-xs text-slate-300">
                        <span className="font-medium">
                          {meta.name} ({meta.sanskrit})
                        </span>
                        <span className="font-mono text-slate-400">{score}%</span>
                      </div>
                      <div className="h-1.5 w-full bg-white/10 rounded-full overflow-hidden">
                        <div
                          className="h-full rounded-full transition-all duration-700"
                          style={{
                            width: `${score}%`,
                            backgroundColor: meta.color,
                          }}
                        />
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* Observations Grid */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 pt-2">
              <div className="p-4 rounded-2xl bg-white/[0.04] border border-white/5 space-y-1">
                <span className="text-[10px] font-semibold uppercase tracking-wider text-[#86868B]">
                  Tatapan & Fokus
                </span>
                <p className="text-xs text-slate-300 leading-relaxed">
                  {result.facialObservations.eyeClarity}
                </p>
              </div>

              <div className="p-4 rounded-2xl bg-white/[0.04] border border-white/5 space-y-1">
                <span className="text-[10px] font-semibold uppercase tracking-wider text-[#86868B]">
                  Rona Vitalitas
                </span>
                <p className="text-xs text-slate-300 leading-relaxed">
                  {result.facialObservations.vitalityTone}
                </p>
              </div>
            </div>

            {/* Strengths & Guidance */}
            <div className="p-5 rounded-2xl bg-white/[0.03] border border-white/5 space-y-2">
              <span className="text-[10px] font-semibold uppercase tracking-wider text-[#86868B]">
                Saran Penyelarasan Energi
              </span>
              <ul className="text-xs text-slate-300 space-y-1.5">
                {result.interpretation.practicalTips.map((tip, i) => (
                  <li key={i} className="flex items-start gap-2">
                    <span className="text-blue-400">•</span>
                    <span>{tip}</span>
                  </li>
                ))}
              </ul>
            </div>

            {/* Bottom Actions */}
            <div className="flex items-center justify-between pt-4 border-t border-white/10">
              <button
                onClick={handleRetake}
                className="flex items-center gap-2 text-xs font-semibold text-[#86868B] hover:text-white transition-colors"
              >
                <RefreshCw className="w-3.5 h-3.5" />
                <span>Ambil Foto Ulang</span>
              </button>

              <button
                onClick={() => {
                  stopCamera();
                  onClose();
                }}
                className="px-6 py-2.5 rounded-full bg-white text-black text-xs font-semibold hover:bg-slate-200 transition-colors"
              >
                Selesai
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};
