"use client";

import { useState } from "react";
import PhotoOverlay from "./PhotoOverlay";
import { Info, Calendar, User, Smartphone, Cpu, Save, Edit2, X, Trash2, Check, Tag } from "lucide-react";
import { API_BASE_URL } from "@/lib/api";
import { useRouter } from "next/navigation";

interface PhotoEditorProps {
  initialPhoto: any;
}

const PREDEFINED_LABELS = ["bullet_hole", "tear", "miss", "rebound", "other"];

export default function PhotoEditor({ initialPhoto }: PhotoEditorProps) {
  const router = useRouter();
  const [isEditing, setIsEditing] = useState(false);
  const [photoData, setPhotoData] = useState(initialPhoto.data);
  const [isSaving, setIsSaving] = useState(false);

  const handleImpactsChange = (newImpacts: any[]) => {
    setPhotoData({
      ...photoData,
      plotting: {
        ...photoData.plotting,
        impacts: newImpacts
      }
    });
  };

  const updateLabel = (index: number, label: string) => {
    const newImpacts = [...photoData.plotting.impacts];
    newImpacts[index] = { ...newImpacts[index], label };
    handleImpactsChange(newImpacts);
  };

  const updateScore = (index: number, score: number) => {
    const newImpacts = [...photoData.plotting.impacts];
    newImpacts[index] = { ...newImpacts[index], score };
    handleImpactsChange(newImpacts);
  };

  const handleSave = async () => {
    setIsSaving(true);
    try {
      const response = await fetch(`${API_BASE_URL}/api/data/${initialPhoto.filename}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(photoData),
      });

      if (response.ok) {
        setIsEditing(false);
        router.refresh();
      } else {
        alert("Erreur lors de la sauvegarde");
      }
    } catch (error) {
      console.error("Save error:", error);
      alert("Erreur réseau");
    } finally {
      setIsSaving(false);
    }
  };

  const impacts = photoData?.plotting?.impacts || [];

  return (
    <div className="grid grid-cols-1 xl:grid-cols-3 gap-8">
      {/* Main View */}
      <div className="xl:col-span-2 space-y-4">
        <div className="flex items-center justify-between bg-slate-900/50 p-4 rounded-xl border border-slate-800">
          <div className="flex items-center gap-3">
            <div className={`w-2 h-2 rounded-full ${isEditing ? 'bg-amber-500 animate-pulse' : 'bg-emerald-500'}`} />
            <span className="text-sm font-medium">
              {isEditing ? "Mode Édition Actif" : "Mode Visualisation"}
            </span>
          </div>
          
          <div className="flex gap-2">
            {isEditing ? (
              <>
                <button 
                  onClick={() => {
                    setPhotoData(initialPhoto.data);
                    setIsEditing(false);
                  }}
                  className="flex items-center gap-2 bg-slate-800 hover:bg-slate-700 px-4 py-2 rounded-lg text-sm font-medium transition-colors"
                >
                  <X size={18} />
                  Annuler
                </button>
                <button 
                  onClick={handleSave}
                  disabled={isSaving}
                  className="flex items-center gap-2 bg-indigo-600 hover:bg-indigo-500 px-4 py-2 rounded-lg text-sm font-medium transition-colors disabled:opacity-50"
                >
                  <Save size={18} />
                  {isSaving ? "Enregistrement..." : "Enregistrer"}
                </button>
              </>
            ) : (
              <button 
                onClick={() => setIsEditing(true)}
                className="flex items-center gap-2 bg-indigo-600 hover:bg-indigo-500 px-4 py-2 rounded-lg text-sm font-medium transition-colors"
              >
                <Edit2 size={18} />
                Modifier les points
              </button>
            )}
          </div>
        </div>

        <PhotoOverlay 
          imageUrl={`${API_BASE_URL}${initialPhoto.imageUrl}`}
          impacts={impacts}
          targetCorners={photoData?.plotting?.target_corners || []}
          isEditing={isEditing}
          onImpactsChange={handleImpactsChange}
        />
      </div>

      {/* Sidebar Info & Labeling */}
      <div className="space-y-6">
        {/* Labeling Section (Only if editing or has impacts) */}
        <div className="bg-slate-900 border border-slate-800 rounded-2xl p-6 space-y-4">
          <div className="flex items-center justify-between pb-4 border-b border-slate-800">
            <div className="flex items-center gap-3">
              <Tag className="text-indigo-400" size={20} />
              <h3 className="font-bold text-lg">Étiquetage (Impacts)</h3>
            </div>
            <span className="bg-slate-800 text-slate-400 text-[10px] font-bold px-2 py-0.5 rounded">
              {impacts.length} TOTAL
            </span>
          </div>

          <div className="space-y-3 max-h-[400px] overflow-auto pr-2 custom-scrollbar">
            {impacts.map((impact: any, index: number) => (
              <div key={impact.id} className="bg-slate-950 p-3 rounded-xl border border-slate-800 space-y-3 group">
                <div className="flex items-center justify-between">
                  <span className="text-[10px] font-bold text-slate-500 uppercase">Impact #{impact.id}</span>
                  {isEditing && (
                    <button 
                      onClick={(e) => {
                        const newImpacts = impacts.filter((_: any, i: number) => i !== index);
                        handleImpactsChange(newImpacts);
                      }}
                      className="text-slate-600 hover:text-rose-500 transition-colors"
                    >
                      <Trash2 size={14} />
                    </button>
                  )}
                </div>

                <div className="grid grid-cols-2 gap-2">
                  <div className="space-y-1">
                    <label className="text-[10px] text-slate-500 font-bold uppercase">Label</label>
                    {isEditing ? (
                      <select 
                        value={impact.label}
                        onChange={(e) => updateLabel(index, e.target.value)}
                        className="w-full bg-slate-900 border border-slate-800 rounded px-2 py-1 text-xs outline-none focus:border-indigo-500"
                      >
                        {PREDEFINED_LABELS.map(l => <option key={l} value={l}>{l}</option>)}
                      </select>
                    ) : (
                      <div className="text-xs text-indigo-300 font-medium">{impact.label}</div>
                    )}
                  </div>
                  <div className="space-y-1">
                    <label className="text-[10px] text-slate-500 font-bold uppercase">Score</label>
                    {isEditing ? (
                      <input 
                        type="number"
                        min="0"
                        max="10"
                        value={impact.score}
                        onChange={(e) => updateScore(index, parseInt(e.target.value) || 0)}
                        className="w-full bg-slate-900 border border-slate-800 rounded px-2 py-1 text-xs outline-none focus:border-indigo-500"
                      />
                    ) : (
                      <div className="text-xs text-emerald-400 font-bold">{impact.score}</div>
                    )}
                  </div>
                </div>
              </div>
            ))}

            {impacts.length === 0 && (
              <p className="text-center py-8 text-xs text-slate-500 italic">
                Aucun impact détecté. {isEditing ? "Cliquez sur l'image pour en ajouter." : ""}
              </p>
            )}
          </div>
        </div>

        {/* Metadata Card (Read Only) */}
        <div className="bg-slate-900/50 border border-slate-800 rounded-2xl p-6 space-y-4 opacity-80">
          <div className="flex items-center gap-3 pb-2 border-b border-slate-800">
            <Info className="text-slate-400" size={18} />
            <h3 className="font-bold text-sm text-slate-300">Métadonnées Session</h3>
          </div>
          <div className="space-y-3">
            <InfoItem icon={<Calendar size={14} />} label="Date" value={photoData ? new Date(photoData.timestamp).toLocaleString() : 'Inconnue'} />
            <InfoItem icon={<User size={14} />} label="Contributeur" value={photoData?.wallet_hash || 'Anonyme'} isMono />
            <InfoItem icon={<Smartphone size={14} />} label="Appareil" value={photoData?.device_info?.model || 'Inconnu'} />
          </div>
        </div>
      </div>
    </div>
  );
}

function InfoItem({ icon, label, value, isMono = false }: any) {
  return (
    <div className="flex flex-col gap-0.5">
      <div className="flex items-center gap-1.5 text-[10px] text-slate-500 font-bold uppercase">
        {icon}
        {label}
      </div>
      <p className={`text-xs text-slate-300 ${isMono ? 'font-mono truncate' : ''}`}>
        {value}
      </p>
    </div>
  );
}
