
import React, { useState, useEffect, useRef } from 'react';
import { Screen, Report } from '../types';
import { GoogleGenAI } from '@google/genai';
import { Language, translations } from '../i18n';

interface NewReportProps {
  navigateTo: (screen: Screen) => void;
  language: Language;
  isOnline: boolean;
  onSave: (report: Omit<Report, 'id'>) => void;
}

const NewReport: React.FC<NewReportProps> = ({ navigateTo, language, isOnline, onSave }) => {
  const [reportText, setReportText] = useState(() => {
    return localStorage.getItem('current_report_draft') || '';
  });
  const [isRefining, setIsRefining] = useState(false);
  const [category, setCategory] = useState<Report['category']>('Algemene observatie');
  
  const t = translations[language].newReport;
  const catT = translations[language].categories;

  useEffect(() => {
    localStorage.setItem('current_report_draft', reportText);
  }, [reportText]);

  const handleSmartRefine = async () => {
    if (!reportText.trim() || !isOnline) return;
    setIsRefining(true);
    try {
      const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
      const prompt = language === 'nl' 
        ? `Herschrijf de volgende medische notities naar een professionele, gestructureerde rapportage in het Nederlands: "${reportText}"`
        : `Rewrite the following medical notes into a professional, structured report in English: "${reportText}"`;
        
      const response = await ai.models.generateContent({
        model: 'gemini-3-flash-preview',
        contents: prompt,
      });
      if (response.text) {
        setReportText(response.text.trim());
      }
    } catch (e) {
      console.error(e);
    } finally {
      setIsRefining(false);
    }
  };

  const handleSave = () => {
    if (!reportText.trim()) return;
    const now = new Date();
    onSave({
      time: now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
      date: language === 'nl' ? `Vandaag, ${now.getDate()} Oct` : `Today, Oct ${now.getDate()}`,
      category,
      content: reportText
    });
    localStorage.removeItem('current_report_draft');
  };

  return (
    <div className="bg-background-light dark:bg-background-dark min-h-[100dvh]">
      <header className="bg-background-light/90 dark:bg-background-dark/90 backdrop-blur-md border-b border-slate-200 dark:border-slate-800 sticky top-0 z-40 px-4 safe-area-pt pb-3 flex items-center justify-between">
        <button onClick={() => navigateTo('clients')} className="text-primary flex items-center gap-1">
          <span className="material-icons">arrow_back</span>
          <span className="font-medium">{t.back}</span>
        </button>
        <h1 className="text-lg font-semibold text-slate-900 dark:text-white">{t.title}</h1>
        <div className="w-12"></div>
      </header>

      <main className="p-4 space-y-6 pb-32">
        <div className="flex items-center gap-3 bg-primary/5 p-3 rounded-xl border border-primary/10">
          <div className="h-12 w-12 rounded-full bg-slate-200 dark:bg-slate-700 flex items-center justify-center text-primary/40">
            <span className="material-icons">account_circle</span>
          </div>
          <div>
            <p className="text-xs text-primary font-bold uppercase tracking-wider">{t.client}</p>
            <p className="font-semibold text-slate-900 dark:text-white">Dhr. J. van der Meer</p>
          </div>
        </div>

        <form className="space-y-5" onSubmit={(e) => e.preventDefault()}>
          <div className="space-y-2">
            <label className="text-sm font-semibold text-slate-700 dark:text-slate-300 ml-1">{t.category}</label>
            <select 
              value={category}
              onChange={(e) => setCategory(e.target.value as any)}
              className="w-full bg-white dark:bg-background-dark border-slate-200 dark:border-slate-700 rounded-lg py-3 px-4 focus:ring-primary focus:border-primary text-slate-900 dark:text-white"
            >
              {Object.entries(catT).map(([key, label]) => (
                <option key={key} value={key}>{label}</option>
              ))}
            </select>
          </div>

          <div className="space-y-2 relative">
            <div className="flex justify-between items-center ml-1">
              <label className="text-sm font-semibold text-slate-700 dark:text-slate-300">{t.reportLabel}</label>
              <button 
                type="button"
                onClick={handleSmartRefine}
                disabled={isRefining || !reportText.trim() || !isOnline}
                className={`flex items-center gap-1 text-[11px] font-bold px-2 py-1 rounded-md transition-all ${
                  (isRefining || !isOnline) ? 'bg-slate-100 text-slate-400' : 'bg-purple-100 text-purple-700'
                }`}
              >
                <span className={`material-icons text-sm ${isRefining ? 'animate-spin' : ''}`}>
                  {isRefining ? 'sync' : 'auto_fix_high'}
                </span>
                {isRefining ? 'Refining...' : t.refine}
              </button>
            </div>
            <textarea 
              value={reportText}
              onChange={(e) => setReportText(e.target.value)}
              className="w-full bg-white dark:bg-background-dark border-slate-200 dark:border-slate-700 rounded-lg py-3 px-4 focus:ring-primary focus:border-primary text-slate-900 dark:text-white placeholder-slate-400" 
              placeholder={t.placeholder} 
              rows={8}
            />
          </div>
        </form>
      </main>

      <footer className="fixed bottom-0 left-0 right-0 p-4 bg-white/80 dark:bg-background-dark/80 backdrop-blur-md border-t border-slate-100 dark:border-slate-800 pb-safe">
        <button 
          onClick={handleSave}
          disabled={!reportText.trim()}
          className={`w-full font-bold py-4 rounded-xl shadow-md transition-all ${
            reportText.trim() ? 'bg-primary text-white active:scale-[0.98]' : 'bg-slate-200 text-slate-400'
          }`}
        >
          {t.save}
        </button>
      </footer>
    </div>
  );
};

export default NewReport;
