
import React, { useState } from 'react';
import { Screen, UserProfile } from '../types';
import { MOCK_BILLABLE } from '../constants';
import { Language, translations } from '../i18n';

interface BillingProps {
  navigateTo: (screen: Screen, clientId?: string, billableIds?: string[]) => void;
  language: Language;
  user: UserProfile | null;
  hourlyRate: number;
  setHourlyRate: (rate: number) => void;
}

const Billing: React.FC<BillingProps> = ({ navigateTo, language, user, hourlyRate, setHourlyRate }) => {
  const [selectedIds, setSelectedIds] = useState<string[]>(MOCK_BILLABLE.filter(b => !b.missingCode).map(b => b.id));
  const [isEditingRate, setIsEditingRate] = useState(false);
  const [tempRate, setTempRate] = useState(hourlyRate.toString());
  
  const t = translations[language].billing;
  const tc = translations[language].common;
  const isAdmin = user?.roleType === 'admin';

  const toggleSelected = (id: string, disabled?: boolean) => {
    if (disabled) return;
    setSelectedIds(prev => 
      prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id]
    );
  };

  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedIds(MOCK_BILLABLE.filter(b => !b.missingCode).map(b => b.id));
    } else {
      setSelectedIds([]);
    }
  };

  const handleExportPdf = () => {
    if (selectedIds.length === 0) return;
    navigateTo('invoice-preview', undefined, selectedIds);
  };

  const saveRate = () => {
    const newRate = parseFloat(tempRate.replace(',', '.'));
    if (!isNaN(newRate) && newRate > 0) {
      setHourlyRate(newRate);
      setIsEditingRate(false);
    }
  };

  const totalAmount = (selectedIds.length * hourlyRate).toFixed(2);
  const formattedAmount = language === 'nl' ? totalAmount.replace('.', ',') : totalAmount;

  return (
    <div className="bg-background-light dark:bg-background-dark min-h-[100dvh] text-slate-800 dark:text-slate-200">
      <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 safe-area-pt pb-4">
        <div className="px-4 flex flex-col gap-2">
          <div className="flex items-center justify-between">
            <button onClick={() => navigateTo('dashboard')} className="p-2 -ml-2 text-primary">
              <span className="material-icons">arrow_back</span>
            </button>
            <h1 className="text-lg font-semibold">{t.title}</h1>
            <button className="text-primary font-medium text-sm">{t.help}</button>
          </div>
          <div className="flex items-center justify-between mt-2">
            <p className="text-xs text-slate-500 dark:text-slate-400 uppercase tracking-wider font-semibold">{t.overview}</p>
            <div className="flex items-center gap-2">
              <span className="text-xs text-slate-500">{t.selectAll}</span>
              <input 
                className="w-5 h-5 rounded border-primary/30 text-primary focus:ring-primary" 
                type="checkbox"
                checked={selectedIds.length === MOCK_BILLABLE.filter(b => !b.missingCode).length && selectedIds.length > 0}
                onChange={(e) => handleSelectAll(e.target.checked)}
              />
            </div>
          </div>
        </div>
      </header>

      <main className="p-4 pb-64 space-y-4">
        {/* Admin Rate Config Section */}
        {isAdmin && (
          <div className="bg-surface-light dark:bg-surface-dark p-4 rounded-xl border border-slate-300 dark:border-slate-800 shadow-sm">
            <div className="flex justify-between items-center">
              <div className="flex items-center gap-2">
                <span className="material-icons text-primary/60">payments</span>
                <span className="text-sm font-bold text-slate-700 dark:text-slate-200">{t.hourlyRate}</span>
              </div>
              {!isEditingRate ? (
                <div className="flex items-center gap-2">
                  <span className="font-mono text-sm font-black text-primary">€ {hourlyRate.toFixed(2).replace('.', ',')}</span>
                  <button 
                    onClick={() => { setTempRate(hourlyRate.toFixed(2)); setIsEditingRate(true); }}
                    className="p-1 text-slate-400 hover:text-primary transition-colors"
                  >
                    <span className="material-icons text-sm">edit</span>
                  </button>
                </div>
              ) : (
                <div className="flex items-center gap-2">
                  <input 
                    type="text"
                    value={tempRate}
                    onChange={(e) => setTempRate(e.target.value)}
                    className="w-20 py-1 px-2 text-xs font-mono border-b border-primary bg-transparent text-primary focus:ring-0 outline-none text-right"
                    autoFocus
                  />
                  <button onClick={saveRate} className="text-primary active:scale-90"><span className="material-icons text-sm">check</span></button>
                  <button onClick={() => setIsEditingRate(false)} className="text-slate-400"><span className="material-icons text-sm">close</span></button>
                </div>
              )}
            </div>
          </div>
        )}

        <div className="bg-primary/10 border border-primary/20 rounded-xl p-4 flex gap-3">
          <span className="material-icons text-primary flex-shrink-0">info</span>
          <div>
            <p className="text-sm font-medium text-primary">{t.infoTitle}</p>
            <p className="text-xs text-slate-600 dark:text-slate-400 leading-relaxed">
              {t.infoBody}
            </p>
          </div>
        </div>

        <div className="space-y-3">
          {MOCK_BILLABLE.map((item) => (
            <div 
              key={item.id}
              onClick={() => toggleSelected(item.id, item.missingCode)}
              className={`bg-white dark:bg-slate-800/50 rounded-xl p-4 shadow-sm border border-slate-100 dark:border-slate-700/50 flex items-center gap-4 ${
                item.missingCode ? 'opacity-70' : 'cursor-pointer active:scale-[0.98]'
              }`}
            >
              <input 
                checked={selectedIds.includes(item.id)}
                disabled={item.missingCode}
                className={`w-6 h-6 rounded border-primary/30 text-primary focus:ring-primary ${item.missingCode ? 'border-slate-300' : ''}`} 
                type="checkbox" 
                readOnly
              />
              <div className="flex-1 min-w-0">
                <div className="flex justify-between items-start mb-1">
                  <h3 className="font-semibold text-slate-900 dark:text-white truncate">{item.clientName}</h3>
                  <span className={`text-xs font-mono px-2 py-0.5 rounded ${
                    item.missingCode 
                      ? 'bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400' 
                      : 'bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-300'
                  }`}>
                    {item.nzaCode}
                  </span>
                </div>
                {!item.missingCode ? (
                  <div className="flex items-center gap-3 text-sm text-slate-500 dark:text-slate-400">
                    <span className="flex items-center gap-1"><span className="material-icons text-[16px]">calendar_today</span> {item.date}</span>
                    <span className="flex items-center gap-1"><span className="material-icons text-[16px]">schedule</span> {item.duration}</span>
                  </div>
                ) : (
                  <p className="text-xs text-red-500 flex items-center gap-1"><span className="material-icons text-xs">warning</span> {t.missingCode}</p>
                )}
              </div>
            </div>
          ))}
        </div>
      </main>

      {/* Floating Action Bar */}
      <div className="fixed bottom-16 left-0 right-0 p-4 bg-background-light/95 dark:bg-background-dark/95 backdrop-blur-md border-t border-primary/10 z-[60] shadow-[0_-10px_20px_rgba(0,0,0,0.05)]">
        <div className="max-w-md mx-auto flex flex-col gap-3">
          <div className="flex items-center justify-between text-sm px-1">
            <span className="text-slate-500 dark:text-slate-400">{selectedIds.length} {t.selected}</span>
            <span className="font-semibold text-slate-900 dark:text-white">{t.total}: € {formattedAmount}</span>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <button className="flex items-center justify-center gap-2 bg-slate-200 dark:bg-slate-700 text-slate-800 dark:text-white py-3.5 rounded-xl font-semibold transition-colors active:scale-95">
              <span className="material-icons text-[20px]">description</span>
              {t.exportCsv}
            </button>
            <button 
              onClick={handleExportPdf}
              disabled={selectedIds.length === 0}
              className="flex items-center justify-center gap-2 bg-primary text-white py-3.5 rounded-xl font-semibold shadow-lg shadow-primary/20 transition-colors active:scale-95 disabled:bg-slate-300 disabled:shadow-none"
            >
              <span className="material-icons text-[20px]">picture_as_pdf</span>
              {t.exportPdf}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Billing;
