"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { User, Download, Save, Award, Activity, Clock, ChevronLeft, ShieldCheck, Target, FileText } from "lucide-react";

export default function PractitionerDetailPage() {
  const params = useParams();
  const router = useRouter();
  const id = params.id as string;
  const [profile, setProfile] = useState<any>(null);
  const [analytics, setAnalytics] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  // Editable fields
  const [mentorNotes, setMentorNotes] = useState("");
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    Promise.all([
      fetch(`/api/profiles/${id}`).then(res => res.json()),
      fetch(`/api/analytics/${id}`).then(res => res.json())
    ]).then(([profileRes, analyticsRes]) => {
      if (profileRes.success) {
        setProfile(profileRes.data);
        setMentorNotes(profileRes.data.mentorNotes || "");
      }
      if (analyticsRes.success) setAnalytics(analyticsRes.data);
      setLoading(false);
    });
  }, [id]);

  const handleSaveNotes = async () => {
    setSaving(true);
    await fetch(`/api/profiles/${id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ mentorNotes }),
    });
    setSaving(false);
  };

  const handleDownloadReport = (type: 'mentor' | 'full') => {
    window.open(`/api/reports/${type}/${id}`, '_blank');
  };

  if (loading) return (
    <div className="h-full flex items-center justify-center font-mono text-[#044f54] uppercase tracking-widest text-xs">
      Retrieving Operative Dossier...
    </div>
  );
  
  if (!profile) return (
    <div className="h-full flex items-center justify-center font-mono text-red-500 uppercase tracking-widest text-xs">
      Operative Not Found in Database.
    </div>
  );

  return (
    <div className="space-y-8 max-w-6xl mx-auto animate-in fade-in duration-500 text-[#044f54]">
      <div className="flex items-center gap-4 border-b border-[#044f54]/20 pb-6">
        <button 
          onClick={() => router.back()}
          className="p-2 rounded bg-[#044f54]/5 text-[#044f54] hover:bg-[#044f54]/10 transition-colors"
        >
          <ChevronLeft size={20} />
        </button>
        <div>
          <h2 className="text-2xl font-serif italic">Operative Dossier</h2>
          <p className="text-[#044f54]/40 text-[10px] font-mono uppercase tracking-[0.2em] mt-1">High-level performance analytics and tracking</p>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        {/* Profile Card */}
        <div className="md:col-span-2 bg-white p-6 rounded border border-[#044f54]/10 shadow-sm flex flex-col md:flex-row justify-between items-start md:items-center gap-6 relative overflow-hidden">
          <div className="absolute top-0 right-0 p-1 opacity-10">
            <div className="w-2 h-2 border-t border-r border-[#044f54]"></div>
          </div>
          
          <div className="flex items-center gap-6">
            <div className="w-20 h-20 rounded bg-[#044f54]/5 border border-[#044f54]/10 flex items-center justify-center text-[#044f54] overflow-hidden">
               {profile.avatar ? <img src={profile.avatar} alt={profile.name} className="w-full h-full object-cover" /> : <User size={40} />}
            </div>
            <div>
              <h3 className="text-xl font-bold uppercase tracking-wider">{profile.name}</h3>
              <div className="flex flex-wrap items-center gap-x-6 gap-y-2 text-[10px] font-mono uppercase tracking-widest text-[#044f54]/60 mt-2">
                <span className="flex items-center gap-1.5"><Clock size={12} className="opacity-40"/> Enrolled {new Date(profile.createdAt).toLocaleDateString()}</span>
                <span className="flex items-center gap-1.5"><ShieldCheck size={12} className="opacity-40"/> {profile.role}</span>
              </div>
              <div className="flex gap-2 mt-4">
                <span className="px-3 py-1 bg-[#044f54]/5 text-[#044f54] text-[9px] font-mono font-bold border border-[#044f54]/10 rounded uppercase tracking-wider">{profile.difficulty} LEVEL</span>
                <span className="px-3 py-1 bg-[#044f54]/5 text-[#044f54] text-[9px] font-mono font-bold border border-[#044f54]/10 rounded uppercase tracking-wider">VOICE: {profile.preferredVoice}</span>
              </div>
            </div>
          </div>

          <div className="flex flex-col gap-3 w-full md:w-auto pt-6 md:pt-0 border-t md:border-t-0 border-[#044f54]/5">
            <button onClick={() => handleDownloadReport('mentor')} className="bg-[#044f54]/5 text-[#044f54] hover:bg-[#044f54]/10 px-6 py-2.5 rounded font-bold uppercase tracking-widest text-[9px] flex items-center justify-center gap-2 transition-all border border-[#044f54]/10">
              <FileText size={14} /> Mentor Dossier
            </button>
            <button onClick={() => handleDownloadReport('full')} className="bg-[#044f54] text-white hover:bg-[#044f54]/90 px-6 py-2.5 rounded font-bold uppercase tracking-widest text-[9px] flex items-center justify-center gap-2 transition-all shadow-lg shadow-[#044f54]/20">
              <Download size={14} /> Full Intel Report
            </button>
          </div>
        </div>

        {/* Analytics Summary */}
        <div className="bg-[#044f54] text-white p-6 rounded shadow-lg shadow-[#044f54]/20 flex flex-col justify-between relative overflow-hidden">
          <div className="absolute inset-0 pointer-events-none bg-[repeating-linear-gradient(0deg,transparent,transparent_2px,rgba(255,255,255,0.05) 2px,rgba(255,255,255,0.05) 4px)]"></div>
          <div>
            <span className="text-[9px] font-mono uppercase tracking-widest opacity-60">Mission Success Rate</span>
            <div className="text-3xl font-black mt-1">
              {analytics ? `${Math.round((analytics.elementsMastered / analytics.totalElements) * 100)}%` : '---'}
            </div>
          </div>
          <div className="mt-8 space-y-4 pt-4 border-t border-white/10">
             <div className="flex justify-between items-center">
                <span className="text-[9px] font-mono uppercase tracking-widest opacity-60">Total Sorties</span>
                <span className="text-sm font-bold">{analytics?.totalSessions || 0}</span>
             </div>
             <div className="flex justify-between items-center">
                <span className="text-[9px] font-mono uppercase tracking-widest opacity-60">Elements Mastered</span>
                <span className="text-sm font-bold">{analytics?.elementsMastered || 0} / {analytics?.totalElements || 0}</span>
             </div>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 pb-12">
        {/* Mentor Notes */}
        <div className="lg:col-span-1 space-y-6">
          <div className="bg-white border border-[#044f54]/10 rounded shadow-sm flex flex-col h-[400px]">
            <div className="px-6 py-4 border-b border-[#044f54]/10 bg-slate-50 flex items-center justify-between">
              <h3 className="font-bold text-[10px] font-mono uppercase tracking-[0.2em]">Sensitive Mentor Notes</h3>
              <Save size={14} className="text-[#044f54]/30" />
            </div>
            <textarea
              value={mentorNotes}
              onChange={(e) => setMentorNotes(e.target.value)}
              className="flex-1 w-full bg-slate-50/30 p-6 text-sm font-serif italic focus:outline-none resize-none leading-relaxed text-[#044f54]/80"
              placeholder="Record confidential observations and coaching feedback here..."
            />
            <div className="p-4 bg-slate-50 border-t border-[#044f54]/5">
              <button 
                onClick={handleSaveNotes}
                disabled={saving}
                className="w-full bg-[#044f54] text-white py-3 rounded font-bold uppercase tracking-widest text-[10px] shadow-md hover:bg-[#044f54]/90 disabled:opacity-50 transition-all flex items-center justify-center gap-2"
              >
                {saving ? (
                   <div className="w-3 h-3 border-2 border-white/20 border-t-white rounded-full animate-spin"></div>
                ) : <Save size={14} />}
                {saving ? "SAVING..." : "COMMIT TO DOSSIER"}
              </button>
            </div>
          </div>
        </div>

        {/* Recent Session Logs */}
        <div className="lg:col-span-2">
          <div className="bg-white rounded border border-[#044f54]/10 shadow-sm overflow-hidden flex flex-col">
            <div className="px-6 py-4 border-b border-[#044f54]/10 bg-slate-50 flex items-center justify-between">
              <h3 className="font-bold text-[10px] font-mono uppercase tracking-[0.2em]">Archived Mission Sorties</h3>
              <Activity size={14} className="text-[#044f54]/30"/>
            </div>
            <div className="divide-y divide-[#044f54]/5 max-h-[400px] overflow-y-auto">
              {profile.sessions.length === 0 ? (
                <div className="p-20 text-center flex flex-col items-center justify-center opacity-30">
                   <Activity size={40} className="mb-4" />
                   <p className="font-mono text-[10px] uppercase tracking-widest">No operational records recovered.</p>
                </div>
              ) : (
                profile.sessions.map((s: any) => (
                  <div key={s.id} className="p-5 px-8 hover:bg-[#044f54]/[0.01] flex items-center justify-between transition-colors cursor-pointer group" onClick={() => router.push(`/admin/sessions/${s.id}`)}>
                    <div className="flex items-center gap-6">
                       <div className="flex flex-col">
                          <span className="text-[10px] font-mono text-[#044f54]/40 uppercase tracking-widest">Mission {s.sessionNumber}</span>
                          <span className="text-sm font-bold text-[#044f54] uppercase">{new Date(s.startTime).toLocaleDateString()}</span>
                       </div>
                       <div className="h-6 w-px bg-[#044f54]/10 hidden sm:block"></div>
                       <div className="hidden sm:flex flex-col">
                          <span className="text-[9px] font-mono text-[#044f54]/40 uppercase tracking-widest">Duration</span>
                          <span className="text-xs font-medium text-[#044f54]/60">{s.endTime ? `${Math.round((new Date(s.endTime).getTime() - new Date(s.startTime).getTime()) / 60000)} MIN` : 'N/A'}</span>
                       </div>
                    </div>
                    <div className="text-right flex items-center gap-6">
                      <div className="flex flex-col">
                         <span className="text-[9px] font-mono text-[#044f54]/40 uppercase tracking-widest">Score</span>
                         <span className="font-black text-[#044f54]">{s.overallScore || '---'}</span>
                      </div>
                      <div className="w-8 h-8 rounded bg-[#044f54]/5 group-hover:bg-[#044f54] group-hover:text-white transition-colors flex items-center justify-center text-[#044f54]">
                         <ChevronLeft size={16} className="rotate-180" />
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
