import React, { useState, useRef, useEffect } from 'react';
import { Camera, Upload, Cloud, Check, X, AlertCircle, RefreshCw, Sparkles, Image as ImageIcon } from 'lucide-react';

interface UserPhotoModalProps {
  isOpen: boolean;
  onClose: () => void;
  currentPhotoUrl?: string;
  userName: string;
  onSavePhoto: (photoUrl: string) => void;
}

// Preset foto profesional berkualitas tinggi
const PRESET_AVATARS = [
  {
    label: 'Pria Eksekutif',
    url: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=200&auto=format&fit=crop&q=80',
  },
  {
    label: 'Wanita Profesional',
    url: 'https://images.unsplash.com/photo-1573496359142-b8d87734a5a2?w=200&auto=format&fit=crop&q=80',
  },
  {
    label: 'Pria Manajemen',
    url: 'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=200&auto=format&fit=crop&q=80',
  },
  {
    label: 'Wanita Akuntan',
    url: 'https://images.unsplash.com/photo-1580489944761-15a19d654956?w=200&auto=format&fit=crop&q=80',
  },
  {
    label: 'Pria Senior Tech',
    url: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=200&auto=format&fit=crop&q=80',
  },
  {
    label: 'Wanita Eksekutif',
    url: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=200&auto=format&fit=crop&q=80',
  },
];

/**
 * Konversi URL Google Drive sharing menjadi direct thumbnail link
 * Contoh: https://drive.google.com/file/d/1A2B3C.../view?usp=sharing
 * -> https://lh3.googleusercontent.com/d/1A2B3C...
 */
export function convertGoogleDriveUrl(url: string): { convertedUrl: string; isGoogleDrive: boolean } {
  const trimmed = url.trim();
  if (!trimmed) return { convertedUrl: '', isGoogleDrive: false };

  // Match /file/d/{id}
  const fileMatch = trimmed.match(/\/file\/d\/([a-zA-Z0-9_-]+)/);
  if (fileMatch && fileMatch[1]) {
    return {
      convertedUrl: `https://lh3.googleusercontent.com/d/${fileMatch[1]}`,
      isGoogleDrive: true,
    };
  }

  // Match id={id}
  const idMatch = trimmed.match(/[?&]id=([a-zA-Z0-9_-]+)/);
  if (idMatch && idMatch[1] && (trimmed.includes('drive.google.com') || trimmed.includes('docs.google.com'))) {
    return {
      convertedUrl: `https://lh3.googleusercontent.com/d/${idMatch[1]}`,
      isGoogleDrive: true,
    };
  }

  return { convertedUrl: trimmed, isGoogleDrive: false };
}

export const UserPhotoModal: React.FC<UserPhotoModalProps> = ({
  isOpen,
  onClose,
  currentPhotoUrl,
  userName,
  onSavePhoto,
}) => {
  const [activeTab, setActiveTab] = useState<'local' | 'cloud' | 'camera'>('local');
  const [previewUrl, setPreviewUrl] = useState<string>(currentPhotoUrl || '');
  const [cloudUrlInput, setCloudUrlInput] = useState<string>('');
  const [isDriveConverted, setIsDriveConverted] = useState(false);
  const [cameraActive, setCameraActive] = useState(false);
  const [cameraError, setCameraError] = useState<string | null>(null);
  const [capturedSnapshot, setCapturedSnapshot] = useState<string | null>(null);

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

  useEffect(() => {
    if (isOpen) {
      setPreviewUrl(currentPhotoUrl || '');
      setCapturedSnapshot(null);
      setCameraError(null);
      setIsDriveConverted(false);
      if (currentPhotoUrl && (currentPhotoUrl.startsWith('http://') || currentPhotoUrl.startsWith('https://'))) {
        setCloudUrlInput(currentPhotoUrl);
      } else {
        setCloudUrlInput('');
      }
    } else {
      stopCamera();
    }
  }, [isOpen, currentPhotoUrl]);

  // Handle webcam stream
  useEffect(() => {
    if (isOpen && activeTab === 'camera') {
      startCamera();
    } else {
      stopCamera();
    }
    return () => {
      stopCamera();
    };
  }, [activeTab, isOpen]);

  const startCamera = async () => {
    setCameraError(null);
    setCapturedSnapshot(null);
    try {
      const stream = await navigator.mediaDevices.getUserMedia({
        video: { width: { ideal: 480 }, height: { ideal: 480 }, facingMode: 'user' },
      });
      streamRef.current = stream;
      if (videoRef.current) {
        videoRef.current.srcObject = stream;
        videoRef.current.play();
      }
      setCameraActive(true);
    } catch (err: unknown) {
      console.error('Camera error:', err);
      setCameraError('Gagal mengakses kamera. Pastikan izin kamera aktif di browser.');
      setCameraActive(false);
    }
  };

  const stopCamera = () => {
    if (streamRef.current) {
      streamRef.current.getTracks().forEach((track) => track.stop());
      streamRef.current = null;
    }
    setCameraActive(false);
  };

  const handleCapturePhoto = () => {
    if (videoRef.current) {
      const canvas = document.createElement('canvas');
      canvas.width = 300;
      canvas.height = 300;
      const ctx = canvas.getContext('2d');
      if (ctx) {
        // Center crop to square
        const v = videoRef.current;
        const minDim = Math.min(v.videoWidth || 300, v.videoHeight || 300);
        const startX = ((v.videoWidth || 300) - minDim) / 2;
        const startY = ((v.videoHeight || 300) - minDim) / 2;

        ctx.drawImage(v, startX, startY, minDim, minDim, 0, 0, 300, 300);
        const dataUrl = canvas.toDataURL('image/jpeg', 0.85);
        setCapturedSnapshot(dataUrl);
        setPreviewUrl(dataUrl);
        stopCamera();
      }
    }
  };

  const handleRetakePhoto = () => {
    setCapturedSnapshot(null);
    startCamera();
  };

  // Local File Upload with Auto-Resize
  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (event) => {
      const img = new Image();
      img.onload = () => {
        const canvas = document.createElement('canvas');
        const maxDim = 320;
        let width = img.width;
        let height = img.height;

        if (width > height) {
          if (width > maxDim) {
            height = Math.round((height * maxDim) / width);
            width = maxDim;
          }
        } else {
          if (height > maxDim) {
            width = Math.round((width * maxDim) / height);
            height = maxDim;
          }
        }

        canvas.width = width;
        canvas.height = height;
        const ctx = canvas.getContext('2d');
        if (ctx) {
          ctx.drawImage(img, 0, 0, width, height);
          const compressed = canvas.toDataURL('image/jpeg', 0.85);
          setPreviewUrl(compressed);
        }
      };
      if (event.target?.result) {
        img.src = event.target.result as string;
      }
    };
    reader.readAsDataURL(file);
  };

  // Cloud / Drive URL Input with Auto-Converter
  const handleCloudUrlChange = (value: string) => {
    setCloudUrlInput(value);
    const { convertedUrl, isGoogleDrive } = convertGoogleDriveUrl(value);
    setIsDriveConverted(isGoogleDrive);
    setPreviewUrl(convertedUrl);
  };

  const handleSelectPreset = (url: string) => {
    setPreviewUrl(url);
    setCloudUrlInput(url);
    setIsDriveConverted(false);
  };

  const handleConfirmSave = () => {
    if (!previewUrl) {
      alert('Silakan pilih atau ambil foto terlebih dahulu!');
      return;
    }
    stopCamera();
    onSavePhoto(previewUrl);
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-60 flex items-center justify-center bg-slate-900/60 p-4 backdrop-blur-xs">
      <div className="w-full max-w-lg rounded-2xl bg-white shadow-2xl overflow-hidden border border-slate-200">
        {/* Header */}
        <div className="flex items-center justify-between border-b border-indigo-700 bg-slate-900 px-5 py-3.5 text-white">
          <div className="flex items-center gap-2.5">
            <div className="rounded-lg bg-indigo-600 p-1.5 text-white">
              <Camera className="h-4 w-4" />
            </div>
            <div>
              <h3 className="text-sm font-bold text-white">
                Foto Profil Pengguna: {userName}
              </h3>
              <p className="text-[11px] text-slate-300">
                Pilih sumber foto: Berkas Lokal, Google Drive / Cloud, atau Kamera Langsung
              </p>
            </div>
          </div>
          <button
            onClick={() => {
              stopCamera();
              onClose();
            }}
            className="rounded-lg p-1 text-slate-400 hover:bg-slate-800 hover:text-white cursor-pointer"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Tab Selection */}
        <div className="flex border-b border-slate-200 bg-slate-50 px-4 pt-2">
          <button
            type="button"
            onClick={() => {
              stopCamera();
              setActiveTab('local');
            }}
            className={`flex items-center gap-1.5 border-b-2 px-3.5 py-2 text-xs font-bold transition-all cursor-pointer ${
              activeTab === 'local'
                ? 'border-indigo-600 text-indigo-700 bg-white rounded-t-lg shadow-2xs'
                : 'border-transparent text-slate-600 hover:text-slate-900'
            }`}
          >
            <Upload className="h-3.5 w-3.5" />
            1. Berkas Lokal (PC / HP)
          </button>
          <button
            type="button"
            onClick={() => {
              stopCamera();
              setActiveTab('cloud');
            }}
            className={`flex items-center gap-1.5 border-b-2 px-3.5 py-2 text-xs font-bold transition-all cursor-pointer ${
              activeTab === 'cloud'
                ? 'border-indigo-600 text-indigo-700 bg-white rounded-t-lg shadow-2xs'
                : 'border-transparent text-slate-600 hover:text-slate-900'
            }`}
          >
            <Cloud className="h-3.5 w-3.5" />
            2. Google Drive / Cloud URL
          </button>
          <button
            type="button"
            onClick={() => {
              setActiveTab('camera');
            }}
            className={`flex items-center gap-1.5 border-b-2 px-3.5 py-2 text-xs font-bold transition-all cursor-pointer ${
              activeTab === 'camera'
                ? 'border-indigo-600 text-indigo-700 bg-white rounded-t-lg shadow-2xs'
                : 'border-transparent text-slate-600 hover:text-slate-900'
            }`}
          >
            <Camera className="h-3.5 w-3.5" />
            3. Kamera Langsung
          </button>
        </div>

        {/* Modal Body */}
        <div className="p-5 space-y-4 max-h-[70vh] overflow-y-auto text-xs">
          {/* Live Preview Box */}
          <div className="flex items-center justify-center p-3 rounded-xl bg-slate-50 border border-slate-200">
            <div className="relative flex flex-col items-center">
              <div className="h-28 w-28 overflow-hidden rounded-full border-3 border-indigo-500 shadow-md bg-white flex items-center justify-center">
                {previewUrl ? (
                  <img
                    src={previewUrl}
                    alt={userName}
                    className="h-full w-full object-cover"
                    onError={() => {
                      // fallback if image link fails
                    }}
                  />
                ) : (
                  <div className="flex flex-col items-center text-slate-400">
                    <ImageIcon className="h-10 w-10 text-slate-300" />
                    <span className="text-[10px] mt-1 font-medium">Belum Ada Foto</span>
                  </div>
                )}
              </div>
              <span className="mt-1.5 text-[11px] font-bold text-slate-700">{userName}</span>
              <span className="text-[10px] text-slate-500">Pratinjau Foto Profil</span>
            </div>
          </div>

          {/* TAB 1: LOCAL FILE */}
          {activeTab === 'local' && (
            <div className="space-y-3">
              <div
                onClick={() => fileInputRef.current?.click()}
                className="border-2 border-dashed border-indigo-300 hover:border-indigo-500 bg-indigo-50/40 rounded-xl p-5 text-center cursor-pointer transition-colors"
              >
                <Upload className="mx-auto h-8 w-8 text-indigo-500 mb-2" />
                <p className="font-bold text-slate-800 text-xs">
                  Klik untuk Memilih Berkas Foto dari Komputer atau HP
                </p>
                <p className="text-[11px] text-slate-500 mt-1">
                  Mendukung format JPG, PNG, WEBP, GIF (Otomatis dioptimalkan)
                </p>
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/*"
                  onChange={handleFileUpload}
                  className="hidden"
                />
              </div>
            </div>
          )}

          {/* TAB 2: GOOGLE DRIVE / CLOUD URL */}
          {activeTab === 'cloud' && (
            <div className="space-y-3">
              <div>
                <label className="block font-semibold text-slate-700 mb-1">
                  Tautan Gambar Web atau Google Drive
                </label>
                <div className="relative">
                  <input
                    type="url"
                    placeholder="https://drive.google.com/file/d/... atau https://..."
                    value={cloudUrlInput}
                    onChange={(e) => handleCloudUrlChange(e.target.value)}
                    className="w-full rounded-lg border border-slate-300 px-3 py-2 text-xs font-mono text-slate-800 focus:border-indigo-500 focus:outline-hidden"
                  />
                </div>
                {isDriveConverted && (
                  <div className="mt-1.5 flex items-center gap-1.5 text-[11px] text-emerald-700 bg-emerald-50 border border-emerald-200 rounded p-1.5 font-medium">
                    <Check className="h-3.5 w-3.5 text-emerald-600 shrink-0" />
                    <span>Tautan Google Drive berhasil dikonversi ke gambar langsung CDN!</span>
                  </div>
                )}
                <p className="mt-1 text-[10px] text-slate-500">
                  Tip: Anda dapat menempel tautan berbagi Google Drive (Pastikan izin file disetel ke &quot;Siapa saja yang memiliki link&quot;).
                </p>
              </div>

              {/* Avatar Presets */}
              <div className="pt-2 border-t border-slate-200">
                <label className="block font-bold text-slate-700 mb-2 flex items-center gap-1.5">
                  <Sparkles className="h-3.5 w-3.5 text-amber-500" />
                  <span>Atau Pilih Koleksi Avatar Profesional Siap Pakai:</span>
                </label>
                <div className="grid grid-cols-3 gap-2">
                  {PRESET_AVATARS.map((p, idx) => (
                    <button
                      key={idx}
                      type="button"
                      onClick={() => handleSelectPreset(p.url)}
                      className={`flex items-center gap-2 p-1.5 rounded-lg border text-left cursor-pointer transition-all ${
                        previewUrl === p.url
                          ? 'border-indigo-600 bg-indigo-50 ring-2 ring-indigo-500/20'
                          : 'border-slate-200 hover:border-slate-300 bg-white'
                      }`}
                    >
                      <img
                        src={p.url}
                        alt={p.label}
                        className="h-8 w-8 rounded-full object-cover shrink-0 border border-slate-200"
                      />
                      <div className="text-[10px] font-semibold text-slate-800 truncate">
                        {p.label}
                      </div>
                    </button>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* TAB 3: LIVE CAMERA */}
          {activeTab === 'camera' && (
            <div className="space-y-3">
              {cameraError ? (
                <div className="rounded-xl border border-rose-200 bg-rose-50 p-4 text-center text-rose-800 space-y-2">
                  <AlertCircle className="mx-auto h-7 w-7 text-rose-600" />
                  <p className="font-bold">{cameraError}</p>
                  <p className="text-[11px] text-rose-700">
                    Periksa izin kamera di ikon gembok pada address bar browser Anda.
                  </p>
                  <button
                    type="button"
                    onClick={startCamera}
                    className="inline-flex items-center gap-1.5 rounded bg-rose-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-rose-700 cursor-pointer"
                  >
                    <RefreshCw className="h-3.5 w-3.5" />
                    Coba Lagi
                  </button>
                </div>
              ) : (
                <div className="flex flex-col items-center justify-center space-y-3">
                  {!capturedSnapshot ? (
                    <div className="relative overflow-hidden rounded-xl border-2 border-indigo-600 bg-slate-950 shadow-inner w-64 h-64 flex items-center justify-center">
                      <video
                        ref={videoRef}
                        autoPlay
                        playsInline
                        muted
                        className="h-full w-full object-cover scale-x-[-1]"
                      />
                      <div className="absolute inset-0 pointer-events-none border-2 border-dashed border-white/40 rounded-full m-4" />
                    </div>
                  ) : (
                    <div className="relative overflow-hidden rounded-xl border-2 border-emerald-600 bg-slate-950 w-64 h-64 flex items-center justify-center">
                      <img
                        src={capturedSnapshot}
                        alt="Captured"
                        className="h-full w-full object-cover scale-x-[-1]"
                      />
                      <span className="absolute top-2 right-2 bg-emerald-600 text-white text-[10px] font-bold px-2 py-0.5 rounded-full">
                        Foto Berhasil Diambil
                      </span>
                    </div>
                  )}

                  <div className="flex gap-2">
                    {!capturedSnapshot ? (
                      <button
                        type="button"
                        onClick={handleCapturePhoto}
                        className="flex items-center gap-2 rounded-lg bg-indigo-600 hover:bg-indigo-700 px-4 py-2 font-bold text-white shadow-xs cursor-pointer transition-colors"
                      >
                        <Camera className="h-4 w-4" />
                        <span>Jepret Foto Sekarang</span>
                      </button>
                    ) : (
                      <div className="flex gap-2">
                        <button
                          type="button"
                          onClick={handleRetakePhoto}
                          className="flex items-center gap-1.5 rounded-lg border border-slate-300 bg-white hover:bg-slate-100 px-3 py-1.5 font-semibold text-slate-700 cursor-pointer"
                        >
                          <RefreshCw className="h-3.5 w-3.5" />
                          <span>Ulangi Jepretan</span>
                        </button>
                        <button
                          type="button"
                          onClick={() => {
                            setPreviewUrl(capturedSnapshot);
                          }}
                          className="flex items-center gap-1.5 rounded-lg bg-emerald-600 hover:bg-emerald-700 px-3 py-1.5 font-bold text-white cursor-pointer"
                        >
                          <Check className="h-3.5 w-3.5" />
                          <span>Gunakan Foto Ini</span>
                        </button>
                      </div>
                    )}
                  </div>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between border-t border-slate-200 bg-slate-50 px-5 py-3">
          <button
            type="button"
            onClick={() => {
              stopCamera();
              onClose();
            }}
            className="rounded-lg px-4 py-2 font-semibold text-slate-600 hover:bg-slate-200 cursor-pointer"
          >
            Batal
          </button>
          <button
            type="button"
            onClick={handleConfirmSave}
            disabled={!previewUrl}
            className="flex items-center gap-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 px-5 py-2 font-bold text-white shadow-xs cursor-pointer transition-colors"
          >
            <Check className="h-4 w-4" />
            <span>Terapkan Foto Profil</span>
          </button>
        </div>
      </div>
    </div>
  );
};
