
import React, { useState, useRef, useEffect } from 'react';
import { Screen, Report, Client, ClientFile } from '../types';
import { Language, translations } from '../i18n';

interface ClientDetailProps {
  navigateTo: (screen: Screen) => void;
  language: Language;
  client: Client;
  reports: Report[];
  onUpdateAssignment: (clientId: string, hospital: string, doctor: string) => void;
  onAddFile: (clientId: string, file: any) => void;
}

type TabType = 'personal' | 'files' | 'plan' | 'report';

const ClientDetail: React.FC<ClientDetailProps> = ({ navigateTo, language, client, reports, onUpdateAssignment, onAddFile }) => {
  const [activeTab, setActiveTab] = useState<TabType>('report');
  const [hospital, setHospital] = useState(client.assignedHospitalId || '');
  const [doctor, setDoctor] = useState(client.assignedDoctor || '');
  const [isSaving, setIsSaving] = useState(false);
  const [viewingFile, setViewingFile] = useState<ClientFile | null>(null);
  const [showCopyFeedback, setShowCopyFeedback] = useState(false);
  const [isDownloading, setIsDownloading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  const t = translations[language].detail;
  const tc = translations[language].common;
  const ts = translations[language].statuses;
  const catT = translations[language].categories;

  useEffect(() => {
    setHospital(client.assignedHospitalId || '');
    setDoctor(client.assignedDoctor || '');
  }, [client.id, client.assignedHospitalId, client.assignedDoctor]);

  const handleSaveReferral = () => {
    if (!hospital.trim() || !doctor.trim()) {
      return;
    }
    
    setIsSaving(true);
    onUpdateAssignment(client.id, hospital, doctor);
    
    setTimeout(() => {
      setIsSaving(false);
    }, 800);
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      onAddFile(client.id, e.target.files[0]);
    }
  };

  const handleViewFile = (file: ClientFile) => {
    setViewingFile(file);
  };

  const handleDownloadFile = (file: ClientFile) => {
    setIsDownloading(true);
    
    // Simulate a secure download process
    setTimeout(() => {
      // Create a mock blob for the file
      const mockContent = `SECURE DOCUMENT: ${file.name}\nClient: ${client.name}\nDate: ${file.uploadDate}\nThis is a secure e-health record.`;
      const blob = new Blob([mockContent], { type: 'text/plain' });
      const url = window.URL.createObjectURL(blob);
      
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', file.name.includes('.') ? file.name : `${file.name}.txt`);
      document.body.appendChild(link);
      link.click();
      
      // Cleanup
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      setIsDownloading(false);
      setViewingFile(null); // Close modal if open
    }, 1000);
  };

  const handleShareFile = async (file: ClientFile) => {
    const shareData = {
      title: file.name,
      text: `${t.viewingDoc}: ${file.name}`,
      url: window.location.href
    };

    if (navigator.share) {
      try {
        await navigator.share(shareData);
      } catch (err) {
        console.log('Share cancelled or failed');
      }
    } else {
      navigator.clipboard.writeText(window.location.href);
      setShowCopyFeedback(true);
      setTimeout(() => setShowCopyFeedback(false), 2000);
    }
  };

  const renderPersonalContent = () => (
    <div className="space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300">
      <div className="bg-surface-light dark:bg-surface-dark p-5 rounded-2xl shadow-sm border border-slate-300 dark:border-slate-800">
        <h3 className="text-sm font-bold text-primary uppercase tracking-wider mb-4 flex items-center gap-2">
          <span className="material-icons text-lg">contact_page</span>
          {language === 'nl' ? 'Contactgegevens' : 'Contact Information'}
        </h3>
        <div className="space-y-4">
          <div className="flex justify-between items-center py-2 border-b border-slate-50 dark:border-slate-700/50">
            <span className="text-sm text-slate-500">{tc.address}</span>
            <span className="text-sm font-medium">{client.address || 'N/A'}</span>
          </div>
          <div className="flex justify-between items-center py-2">
            <span className="text-sm text-slate-500">{tc.phone}</span>
            <a href="tel:0612345678" className="text-sm font-bold text-primary">06 12345678</a>
          </div>
        </div>
      </div>

      <div className="bg-surface-light dark:bg-surface-dark p-5 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-800">
        <div className="flex justify-between items-center mb-4">
          <h3 className="text-sm font-bold text-primary uppercase tracking-wider flex items-center gap-2">
            <span className="material-icons text-lg">medical_services</span>
            {t.referralTitle}
          </h3>
          {client.assignedHospitalId && (
            <span className="flex items-center gap-1 text-[10px] font-bold text-green-500 uppercase animate-pulse">
              <span className="material-icons text-sm">verified</span>
              {tc.verified}
            </span>
          )}
        </div>
        <div className="space-y-4">
          <div className="space-y-1.5">
            <label className="text-xs font-bold text-slate-400 uppercase tracking-tight">{tc.hospital}</label>
            <input 
              value={hospital}
              onChange={e => setHospital(e.target.value)}
              placeholder={t.institutionPlaceholder}
              className="w-full bg-slate-50 dark:bg-slate-900 border-none rounded-xl py-3.5 px-4 text-sm text-slate-900 dark:text-white focus:ring-2 focus:ring-primary/40 outline-none transition-all"
            />
          </div>
          <div className="space-y-1.5">
            <label className="text-xs font-bold text-slate-400 uppercase tracking-tight">{tc.doctor}</label>
            <input 
              value={doctor}
              onChange={e => setDoctor(e.target.value)}
              placeholder={t.doctorPlaceholder}
              className="w-full bg-slate-50 dark:bg-slate-900 border-none rounded-xl py-3.5 px-4 text-sm text-slate-900 dark:text-white focus:ring-2 focus:ring-primary/40 outline-none transition-all"
            />
          </div>
          <button 
            onClick={handleSaveReferral}
            disabled={isSaving || (!hospital.trim() && !doctor.trim())}
            className={`w-full font-black py-4 rounded-2xl text-sm transition-all flex items-center justify-center gap-2 shadow-xl ${
              isSaving 
                ? 'bg-slate-100 text-slate-400 cursor-not-allowed' 
                : 'bg-primary text-white active:scale-95 shadow-primary/20 hover:brightness-110'
            }`}
          >
            {isSaving ? (
              <span className="material-icons animate-spin">refresh</span>
            ) : (
              <span className="material-icons">save</span>
            )}
            {isSaving ? tc.loading : t.saveAssignment}
          </button>
        </div>
      </div>
    </div>
  );

  const renderFilesContent = () => (
    <div className="space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300">
      <div className="bg-primary/5 p-4 rounded-xl border border-primary/10 flex gap-3">
        <span className="material-icons text-primary">security</span>
        <p className="text-xs text-slate-600 dark:text-slate-400 leading-relaxed font-medium">
          {t.filePrivacyNote}
        </p>
      </div>

      <div className="space-y-3">
        {(client.files && client.files.length > 0) ? (
          client.files.map(file => (
            <div key={file.id} className="bg-surface-light dark:bg-surface-dark p-4 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-800 flex items-center justify-between group hover:border-primary/40 transition-all">
              <div className="flex items-center gap-3 min-w-0">
                <div className={`w-12 h-12 rounded-xl flex items-center justify-center ${file.type === 'pdf' ? 'bg-red-50 text-red-500' : 'bg-blue-50 text-blue-500'}`}>
                  <span className="material-icons text-2xl">{file.type === 'pdf' ? 'picture_as_pdf' : 'description'}</span>
                </div>
                <div className="min-w-0">
                  <h4 className="text-sm font-black truncate text-slate-800 dark:text-slate-200">{file.name}</h4>
                  <p className="text-[10px] text-slate-400 font-bold uppercase tracking-wider">{file.uploadDate} • {file.size}</p>
                </div>
              </div>
              <div className="flex gap-1">
                <button 
                  onClick={() => handleViewFile(file)}
                  className="w-10 h-10 flex items-center justify-center text-slate-400 hover:text-primary hover:bg-primary/10 rounded-xl transition-all"
                  title="Preview"
                >
                  <span className="material-icons text-xl">visibility</span>
                </button>
                <button 
                  onClick={() => handleDownloadFile(file)}
                  className="w-10 h-10 flex items-center justify-center text-slate-400 hover:text-primary hover:bg-primary/10 rounded-xl transition-all"
                  title="Download"
                >
                  <span className="material-icons text-xl">cloud_download</span>
                </button>
                <button 
                  onClick={() => handleShareFile(file)}
                  className="w-10 h-10 flex items-center justify-center text-slate-400 hover:text-primary hover:bg-primary/10 rounded-xl transition-all"
                  title="Share"
                >
                  <span className="material-icons text-xl">share</span>
                </button>
              </div>
            </div>
          ))
        ) : (
          <div className="text-center py-16 bg-slate-50 dark:bg-slate-800/20 rounded-3xl border-2 border-dashed border-slate-200 dark:border-slate-700">
             <span className="material-icons text-slate-300 text-5xl mb-3">folder_open</span>
             <p className="text-sm text-slate-400 font-bold uppercase tracking-widest">{tc.noDocuments}</p>
          </div>
        )}
      </div>

      <input 
        type="file" 
        ref={fileInputRef} 
        className="hidden" 
        onChange={handleFileChange}
      />
      <button 
        onClick={() => fileInputRef.current?.click()}
        className="w-full border-2 border-dashed border-primary/30 text-primary p-8 rounded-3xl flex flex-col items-center gap-3 hover:bg-primary/5 transition-all active:scale-[0.98] group"
      >
        <div className="w-14 h-14 rounded-full bg-primary/10 flex items-center justify-center group-hover:scale-110 transition-transform">
          <span className="material-icons text-3xl">upload_file</span>
        </div>
        <span className="text-sm font-black uppercase tracking-widest">{t.uploadBtn}</span>
      </button>

      {(showCopyFeedback || isDownloading) && (
        <div className="fixed bottom-24 left-1/2 -translate-x-1/2 bg-slate-900 text-white px-6 py-3 rounded-full text-xs font-bold shadow-2xl animate-in fade-in slide-in-from-bottom-4 z-[100] flex items-center gap-2">
          {isDownloading && <span className="material-icons text-sm animate-spin">refresh</span>}
          {isDownloading ? t.downloading : t.linkCopied}
        </div>
      )}
    </div>
  );

  const renderPlanContent = () => (
    <div className="space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300">
      <div className="bg-surface-light dark:bg-surface-dark p-5 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-800">
        <h3 className="text-sm font-bold text-primary uppercase tracking-wider mb-4 flex items-center gap-2">
          <span className="material-icons text-lg">checklist</span>
          {tc.attention}
        </h3>
        <div className="space-y-4">
          <div className="p-5 bg-primary/5 rounded-2xl border border-primary/10">
            <div className="flex justify-between items-start mb-3">
              <p className="text-xs font-black text-primary uppercase tracking-widest">{t.selfReliance}</p>
              <div className="h-2 w-24 bg-slate-200 dark:bg-slate-700 rounded-full overflow-hidden">
                <div className="h-full bg-primary w-3/4"></div>
              </div>
            </div>
            <p className="text-sm text-slate-700 dark:text-slate-300 leading-relaxed font-medium">
              {language === 'nl' 
                ? 'Client kan zelfstandig ochtendmedicatie innemen met behulp van Medido. Volgende evaluatie gepland voor december 2024.'
                : 'Client can independently take morning medication with help from Medido. Next evaluation planned for December 2024.'}
            </p>
          </div>
        </div>
      </div>
    </div>
  );

  const renderReportContent = () => (
    <div className="space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300">
      {reports.length > 0 ? (
        reports.map((report) => (
          <div key={report.id} className="relative pl-6 border-l-2 border-primary/30">
            <div className="absolute -left-[9px] top-0 w-4 h-4 rounded-full border-4 border-background-light dark:border-background-dark bg-primary shadow-sm"></div>
            <div className="bg-surface-light dark:bg-surface-dark p-5 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-800">
              <div className="flex justify-between items-start mb-3">
                <div className="flex items-center gap-2">
                  <span className="text-[10px] font-black text-slate-400 uppercase tracking-tighter">{report.time} • {report.date}</span>
                  <span className={`px-2 py-0.5 rounded-lg text-[9px] font-black uppercase tracking-widest ${
                    report.category === 'Incident' ? 'bg-red-100 text-red-600' : 'bg-primary/10 text-primary'
                  }`}>
                    {catT[report.category] || report.category}
                  </span>
                </div>
              </div>
              <p className="text-sm text-slate-700 dark:text-slate-200 leading-relaxed whitespace-pre-line font-medium">
                {report.content}
              </p>
            </div>
          </div>
        ))
      ) : (
        <div className="text-center py-20 bg-slate-50 dark:bg-slate-800/20 rounded-3xl">
          <span className="material-icons text-5xl text-slate-200 mb-3">history_edu</span>
          <p className="text-sm text-slate-400 font-bold uppercase tracking-widest">{tc.noReports}</p>
        </div>
      )}
    </div>
  );

  return (
    <div className="bg-background-light dark:bg-background-dark min-h-[100dvh]">
      <header className="sticky top-0 z-50 bg-background-light/90 dark:bg-background-dark/90 backdrop-blur-md border-b border-slate-300 dark:border-slate-800 px-4 safe-area-pt pb-3 shadow-sm">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-4">
            <button 
               onClick={() => navigateTo('clients')} 
               className="w-10 h-10 flex items-center justify-center text-slate-400 hover:text-primary hover:bg-primary/10 rounded-xl transition-all active:scale-95"
               title={language === 'nl' ? 'Terug' : 'Back'}
             >
               <span className="material-icons">arrow_back</span>
             </button>
            <div className="w-14 h-14 rounded-2xl bg-gradient-to-br from-primary/20 to-primary/5 flex items-center justify-center border border-primary/20 text-primary shadow-inner">
              <span className="material-icons text-3xl">person</span>
            </div>
            <div>
              <div className="flex items-center gap-2">
                <h1 className="text-lg font-black text-slate-900 dark:text-white leading-tight tracking-tight">{client.name}</h1>
                <span className={`text-[8px] font-black uppercase px-1.5 py-0.5 rounded-full ${
                  client.status === 'Stabiel' ? 'bg-green-100 text-green-600' : 'bg-red-100 text-red-600'
                }`}>
                  {ts[client.status] || client.status}
                </span>
              </div>
              <p className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest">{client.age} YRS • {client.birthDate}</p>
            </div>
          </div>
        </div>

        <nav className="flex p-1.5 bg-slate-100 dark:bg-slate-800/80 rounded-2xl overflow-x-auto no-scrollbar gap-1">
          {[
            { id: 'personal', icon: 'badge', label: t.personal },
            { id: 'files', icon: 'folder_zip', label: t.files },
            { id: 'plan', icon: 'verified_user', label: t.plan },
            { id: 'report', icon: 'description', label: t.report }
          ].map((tab) => (
            <button 
              key={tab.id}
              onClick={() => setActiveTab(tab.id as TabType)}
              className={`flex-1 min-w-[85px] py-2 text-[9px] font-black uppercase tracking-widest rounded-xl transition-all flex flex-col items-center gap-1 ${
                activeTab === tab.id 
                  ? 'bg-white dark:bg-primary shadow-sm text-primary dark:text-white scale-[1.02]' 
                  : 'text-slate-400 dark:text-slate-500'
              }`}
            >
              <span className="material-icons text-lg">{tab.icon}</span>
              {tab.label}
            </button>
          ))}
        </nav>
      </header>

      <main className="px-4 py-6 pb-40">
        {activeTab === 'personal' && renderPersonalContent()}
        {activeTab === 'files' && renderFilesContent()}
        {activeTab === 'plan' && renderPlanContent()}
        {activeTab === 'report' && renderReportContent()}
      </main>

      {viewingFile && (
        <div className="fixed inset-0 z-[100] flex flex-col items-center justify-center p-4 bg-slate-900/90 backdrop-blur-sm animate-in fade-in duration-300">
          <div className="w-full max-w-[90%] md:max-w-lg bg-white dark:bg-slate-900 rounded-[2.5rem] overflow-hidden shadow-2xl flex flex-col max-h-[85vh]">
            <div className="p-6 border-b border-slate-100 dark:border-slate-800 flex justify-between items-center bg-slate-50 dark:bg-slate-900/50">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-primary/10 text-primary flex items-center justify-center">
                  <span className="material-icons">{viewingFile.type === 'pdf' ? 'picture_as_pdf' : 'description'}</span>
                </div>
                <div>
                  <h2 className="text-sm font-black truncate max-w-[150px] md:max-w-[200px]">{viewingFile.name}</h2>
                  <p className="text-[10px] text-slate-400 font-bold uppercase tracking-widest">{viewingFile.size} • Encrypted</p>
                </div>
              </div>
              <button 
                onClick={() => setViewingFile(null)}
                className="w-10 h-10 flex items-center justify-center text-slate-400 hover:text-red-500 rounded-full bg-white dark:bg-slate-800 shadow-sm transition-all"
              >
                <span className="material-icons">close</span>
              </button>
            </div>
            
            <div className="flex-grow overflow-y-auto p-6 bg-slate-50 dark:bg-slate-800/30">
              <div className="w-full aspect-[3/4] bg-white dark:bg-slate-900 rounded-2xl shadow-inner border border-slate-100 dark:border-slate-800 flex flex-col items-center justify-center p-10 text-center space-y-4">
                <span className="material-icons text-6xl text-slate-200">shield</span>
                <div className="space-y-2">
                  <p className="text-sm font-black text-slate-400 uppercase tracking-widest">{t.securePreview}</p>
                  <p className="text-xs text-slate-400 leading-relaxed italic">
                    {t.securePreviewNote}
                  </p>
                </div>
                <div className="w-full max-w-[200px] h-1 bg-slate-100 dark:bg-slate-800 rounded-full overflow-hidden">
                   <div className="h-full bg-primary w-full animate-pulse"></div>
                </div>
              </div>
            </div>

            <div className="p-6 bg-white dark:bg-slate-900 border-t border-slate-100 dark:border-slate-800">
              <button 
                onClick={() => handleDownloadFile(viewingFile)}
                disabled={isDownloading}
                className="w-full py-4 bg-primary text-white font-black rounded-2xl shadow-xl shadow-primary/20 flex items-center justify-center gap-3 active:scale-95 transition-all disabled:opacity-50"
              >
                <span className={`material-icons ${isDownloading ? 'animate-spin' : ''}`}>
                  {isDownloading ? 'refresh' : 'cloud_download'}
                </span>
                {isDownloading ? tc.loading : t.secureDownload}
              </button>
            </div>
          </div>
        </div>
      )}

      {activeTab === 'report' && (
        <div className="fixed bottom-20 inset-x-0 p-4 bg-gradient-to-t from-background-light dark:from-background-dark z-50 pt-10">
          <div className="flex gap-3 max-w-md mx-auto pointer-events-auto pb-safe">
            <button 
              onClick={() => navigateTo('new-report')}
              className="w-full py-4 bg-primary hover:bg-primary/90 text-white font-black rounded-2xl shadow-xl shadow-primary/30 flex items-center justify-center gap-2 transition-all active:scale-[0.98]"
            >
              <span className="material-icons text-xl">add_circle</span>
              {t.newReport}
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default ClientDetail;
