
import React, { useState, useEffect } from 'react';
import { Screen, Report, Client, WorkLog, StaffMember, UserProfile, BillableActivity, RoleType, CompanyProfile } from './types.ts';
import { Language, translations } from './i18n.ts';
import { MOCK_REPORTS, MOCK_CLIENTS } from './constants.ts';
import Login from './pages/Login.tsx';
import Signup from './pages/Signup.tsx';
import Dashboard from './pages/Dashboard.tsx';
import ClientList from './pages/ClientList.tsx';
import ClientDetail from './pages/ClientDetail.tsx';
import NewReport from './pages/NewReport.tsx';
import Billing from './pages/Billing.tsx';
import Profile from './pages/Profile.tsx';
import AddClient from './pages/AddClient.tsx';
import AddStaff from './pages/AddStaff.tsx';
import StaffManagement from './pages/StaffManagement.tsx';
import TimeLogs from './pages/TimeLogs.tsx';
import InvoicePreview from './pages/InvoicePreview.tsx';
import AdminSettings from './pages/AdminSettings.tsx';

const STORAGE_KEYS = {
  USER: 'zorgportaal_user',
  ALL_USERS: 'zorgportaal_all_users',
  CLIENTS: 'zorgportaal_clients',
  REPORTS: 'zorgportaal_reports',
  LOGS: 'zorgportaal_logs',
  LANG: 'zorgportaal_lang',
  HOURLY_RATE: 'zorgportaal_hourly_rate',
  COMPANY: 'zorgportaal_company'
};

const DEFAULT_COMPANY: CompanyProfile = {
  name: 'ZorgPortaal B.V.',
  logoUrl: 'https://fonts.gstatic.com/s/i/materialiconsround/health_and_safety/v12/24px.svg',
  address: 'Dorpsstraat 4, 3512 AB Utrecht, Nederland',
  email: 'info@zorgportaal.nl',
  phone: '0800-ZORG-123',
  kvk: '12345678',
  btw: 'NL123456789B01',
  iban: 'NL99 BANK 0123 4567 89',
  invoiceFooter: 'Bedankt voor uw vertrouwen in onze zorgverlening. Betaaltermijn is 14 dagen na factuurdatum.'
};

const App: React.FC = () => {
  const [screen, setScreen] = useState<Screen>('login');
  const [selectedClientId, setSelectedClientId] = useState<string | null>(null);
  const [selectedBillableIds, setSelectedBillableIds] = useState<string[]>([]);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  
  const [companyProfile, setCompanyProfile] = useState<CompanyProfile>(() => {
    const saved = localStorage.getItem(STORAGE_KEYS.COMPANY);
    return saved ? JSON.parse(saved) : DEFAULT_COMPANY;
  });

  const [allUsers, setAllUsers] = useState<UserProfile[]>(() => {
    const saved = localStorage.getItem(STORAGE_KEYS.ALL_USERS);
    return saved ? JSON.parse(saved) : [
      { 
        id: 'admin-1', 
        fullName: 'Admin User', 
        email: 'admin@careportal.com', 
        password: 'admin',
        bigNumber: '12345678901', 
        roleType: 'admin', 
        status: 'active', 
        role: 'Systeembeheerder',
        workLat: 52.0907, 
        workLng: 5.1214 
      }
    ];
  });

  const [user, setUser] = useState<UserProfile | null>(() => {
    const saved = localStorage.getItem(STORAGE_KEYS.USER);
    return saved ? JSON.parse(saved) : null;
  });
  
  const [language, setLanguage] = useState<Language>(() => {
    const saved = localStorage.getItem(STORAGE_KEYS.LANG);
    return (saved as Language) || 'nl';
  });

  const [hourlyRate, setHourlyRate] = useState<number>(() => {
    const saved = localStorage.getItem(STORAGE_KEYS.HOURLY_RATE);
    return saved ? parseFloat(saved) : 71.25;
  });
  
  const [isOnline, setIsOnline] = useState(navigator.onLine);
  
  const [reports, setReports] = useState<Report[]>(() => {
    const saved = localStorage.getItem(STORAGE_KEYS.REPORTS);
    return saved ? JSON.parse(saved) : MOCK_REPORTS;
  });

  const [clients, setClients] = useState<Client[]>(() => {
    const saved = localStorage.getItem(STORAGE_KEYS.CLIENTS);
    return saved ? JSON.parse(saved) : MOCK_CLIENTS;
  });

  const [workLogs, setWorkLogs] = useState<WorkLog[]>(() => {
    const saved = localStorage.getItem(STORAGE_KEYS.LOGS);
    return saved ? JSON.parse(saved) : [];
  });

  const t = translations[language];

  useEffect(() => {
    if (user) {
      setIsLoggedIn(true);
      setScreen('dashboard');
    }
  }, []);

  useEffect(() => {
    localStorage.setItem(STORAGE_KEYS.COMPANY, JSON.stringify(companyProfile));
  }, [companyProfile]);

  useEffect(() => {
    localStorage.setItem(STORAGE_KEYS.ALL_USERS, JSON.stringify(allUsers));
  }, [allUsers]);

  useEffect(() => {
    if (user) {
      localStorage.setItem(STORAGE_KEYS.USER, JSON.stringify(user));
    } else {
      localStorage.removeItem(STORAGE_KEYS.USER);
    }
  }, [user]);

  useEffect(() => {
    localStorage.setItem(STORAGE_KEYS.CLIENTS, JSON.stringify(clients));
  }, [clients]);

  useEffect(() => {
    localStorage.setItem(STORAGE_KEYS.REPORTS, JSON.stringify(reports));
  }, [reports]);

  useEffect(() => {
    localStorage.setItem(STORAGE_KEYS.LOGS, JSON.stringify(workLogs));
  }, [workLogs]);

  useEffect(() => {
    localStorage.setItem(STORAGE_KEYS.LANG, language);
  }, [language]);

  useEffect(() => {
    localStorage.setItem(STORAGE_KEYS.HOURLY_RATE, hourlyRate.toString());
  }, [hourlyRate]);

  useEffect(() => {
    const handleOnline = () => setIsOnline(true);
    const handleOffline = () => setIsOnline(false);
    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);
    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, []);

  const navigateTo = (newScreen: Screen, clientId?: string, billableIds?: string[]) => {
    if (user?.roleType === 'staff') {
      const adminOnlyScreens: Screen[] = ['billing', 'staff', 'invoice-preview', 'admin-settings'];
      if (adminOnlyScreens.includes(newScreen)) {
        console.warn('Access denied for staff role');
        return;
      }
    }

    if (clientId) setSelectedClientId(clientId);
    if (billableIds) setSelectedBillableIds(billableIds);
    setScreen(newScreen);
    window.scrollTo(0, 0);
  };

  const handleLogin = (userData: UserProfile) => {
    setUser(userData);
    setIsLoggedIn(true);
    navigateTo('dashboard');
  };

  const handleSignup = (userData: UserProfile) => {
    const userWithLocation = { ...userData, workLat: 52.0907, workLng: 5.1214 };
    setAllUsers(prev => [...prev, userWithLocation]);
  };

  const handleUpdatePassword = (userId: string, newPassword: string) => {
    setAllUsers(prev => prev.map(u => 
      u.id === userId ? { ...u, password: newPassword } : u
    ));
    if (user?.id === userId) {
      setUser(prev => prev ? { ...prev, password: newPassword } : null);
    }
  };

  const handleApproveUser = (userId: string) => {
    setAllUsers(prev => prev.map(u => 
      u.id === userId ? { ...u, status: 'active' as const } : u
    ));
  };

  const handleRejectUser = (userId: string) => {
    setAllUsers(prev => prev.filter(u => u.id !== userId));
  };

  const handleLogout = () => {
    setUser(null);
    setIsLoggedIn(false);
    localStorage.removeItem(STORAGE_KEYS.USER);
    navigateTo('login');
  };

  const handleSaveReport = (newReport: Omit<Report, 'id'>) => {
    const activeId = selectedClientId || 'unknown';
    const reportWithId: Report = { ...newReport, id: `r-${activeId}-${Date.now()}` };
    setReports(prev => [reportWithId, ...prev]);
    navigateTo('client-detail');
  };

  const handleAddClient = (newClient: Omit<Client, 'id' | 'age' | 'lastVisit'>) => {
    const birthYear = new Date(newClient.birthDate).getFullYear();
    const age = new Date().getFullYear() - birthYear;
    const dateObj = new Date(newClient.birthDate);
    const birthDateStr = `${String(dateObj.getDate()).padStart(2, '0')}-${String(dateObj.getMonth() + 1).padStart(2, '0')}-${dateObj.getFullYear()}`;

    const clientWithId: Client = {
      ...newClient,
      id: `c-${Date.now()}`,
      age: age,
      birthDate: birthDateStr,
      lastVisit: language === 'nl' ? 'Nog niet bezocht' : 'Not yet visited',
      files: []
    };
    setClients(prev => [clientWithId, ...prev]);
    navigateTo('clients');
  };

  const handleAddStaff = (newStaff: Omit<UserProfile, 'id' | 'status'>) => {
    const staffWithId: UserProfile = {
      ...newStaff,
      id: `u-${Date.now()}`,
      status: 'active'
    };
    setAllUsers(prev => [...prev, staffWithId]);
    navigateTo('staff');
  };

  const handleDeleteClient = (id: string) => {
    if (user?.roleType !== 'admin') return;
    setClients(prev => prev.filter(client => client.id !== id));
  };

  const handleUpdateAssignment = (clientId: string, hospital: string, doctor: string) => {
    setClients(prev => prev.map(c => 
      c.id === clientId ? { ...c, assignedHospitalId: hospital, assignedDoctor: doctor } : c
    ));
  };

  const handleUpdateStaffAssignment = (staffId: string, clientId: string, lat: number, lng: number) => {
    setAllUsers(prev => prev.map(u => 
      u.id === staffId ? { ...u, workLat: lat, workLng: lng } : u
    ));

    setClients(prev => prev.map(c => 
      c.id === clientId ? { ...c, assignedStaffId: staffId } : c
    ));

    if (user?.id === staffId) {
      setUser({ ...user, workLat: lat, workLng: lng });
    }
  };

  const handleAddFile = (clientId: string, file: any) => {
    setClients(prev => prev.map(c => {
      if (c.id === clientId) {
        const newFile = {
          id: `f-${Date.now()}`,
          name: file.name,
          type: file.name.toLowerCase().endsWith('.pdf') ? 'pdf' : (file.name.toLowerCase().endsWith('.doc') || file.name.toLowerCase().endsWith('.docx') ? 'doc' : 'img'),
          uploadDate: new Date().toLocaleDateString(),
          size: `${(file.size / 1024 / 1024).toFixed(2)} MB`
        };
        return { ...c, files: [...(c.files || []), newFile] };
      }
      return c;
    }));
  };

  if (!isLoggedIn) {
    if (screen === 'signup') return <Signup onSignup={handleSignup} language={language} setLanguage={setLanguage} navigateTo={navigateTo} />;
    return (
      <Login 
        onLogin={handleLogin} 
        language={language} 
        setLanguage={setLanguage} 
        navigateTo={navigateTo} 
        allUsers={allUsers} 
        companyName={companyProfile.name}
        logoUrl={companyProfile.logoUrl}
      />
    );
  }

  const renderScreen = () => {
    const commonProps = { navigateTo, language, isOnline, user };
    switch (screen) {
      case 'dashboard': return <Dashboard {...commonProps} allUsers={allUsers} clients={clients} workLogs={workLogs} onAssign={handleUpdateStaffAssignment} companyProfile={companyProfile} />;
      case 'clients': return <ClientList {...commonProps} clients={clients} onDeleteClient={handleDeleteClient} />;
      case 'client-detail': {
        const activeClient = clients.find(c => c.id === selectedClientId) || clients[0];
        return <ClientDetail {...commonProps} client={activeClient} reports={reports.filter(r => r.id.includes(activeClient.id))} onUpdateAssignment={handleUpdateAssignment} onAddFile={handleAddFile} />;
      }
      case 'new-report': return <NewReport {...commonProps} onSave={handleSaveReport} />;
      case 'staff': return <StaffManagement {...commonProps} allUsers={allUsers} onApprove={handleApproveUser} onReject={handleRejectUser} />;
      case 'time-logs': return <TimeLogs {...commonProps} logs={workLogs} onAddLog={(log) => setWorkLogs([log, ...workLogs])} />;
      case 'billing': return <Billing {...commonProps} hourlyRate={hourlyRate} setHourlyRate={setHourlyRate} />;
      case 'profile': return <Profile {...commonProps} setLanguage={setLanguage} onLogout={handleLogout} onUpdatePassword={handleUpdatePassword} />;
      case 'add-client': return <AddClient {...commonProps} onAdd={handleAddClient} />;
      case 'add-staff': return <AddStaff {...commonProps} onAdd={handleAddStaff} />;
      case 'invoice-preview': return <InvoicePreview {...commonProps} selectedBillableIds={selectedBillableIds} hourlyRate={hourlyRate} companyProfile={companyProfile} />;
      case 'admin-settings': return <AdminSettings {...commonProps} companyProfile={companyProfile} setCompanyProfile={setCompanyProfile} />;
      default: return <Dashboard {...commonProps} allUsers={allUsers} clients={clients} workLogs={workLogs} onAssign={handleUpdateStaffAssignment} companyProfile={companyProfile} />;
    }
  };

  const isAdmin = user?.roleType === 'admin';

  return (
    <div className="flex flex-col min-h-[100dvh] bg-background-light dark:bg-background-dark overflow-x-hidden w-full">
      <div className="flex-grow w-full max-w-md mx-auto relative">{renderScreen()}</div>
      
      {['dashboard', 'clients', 'staff', 'time-logs', 'billing'].includes(screen) && (
        <nav className="fixed bottom-0 left-0 right-0 bg-surface-light/95 dark:bg-surface-dark/95 backdrop-blur-md border-t border-slate-300 dark:border-slate-800 safe-area-bottom z-50 print:hidden w-full max-w-md mx-auto shadow-[0_-4px_12px_rgba(0,0,0,0.1)]">
          <div className="flex justify-around items-center h-16">
            <button onClick={() => navigateTo('dashboard')} className={`flex flex-col items-center ${screen === 'dashboard' ? 'text-primary' : 'text-slate-400'}`}>
              <span className="material-icons">home</span>
              <span className="text-[10px]">{t.nav.dashboard}</span>
            </button>
            <button onClick={() => navigateTo('clients')} className={`flex flex-col items-center ${screen === 'clients' ? 'text-primary' : 'text-slate-400'}`}>
              <span className="material-icons">assignment_ind</span>
              <span className="text-[10px]">{t.nav.clients}</span>
            </button>
            {isAdmin && (
              <button onClick={() => navigateTo('staff')} className={`flex flex-col items-center ${screen === 'staff' ? 'text-primary' : 'text-slate-400'}`}>
                <span className="material-icons">group</span>
                <span className="text-[10px]">{t.nav.staff}</span>
              </button>
            )}
            <button onClick={() => navigateTo('time-logs')} className={`flex flex-col items-center ${screen === 'time-logs' ? 'text-primary' : 'text-slate-400'}`}>
              <span className="material-icons">timer</span>
              <span className="text-[10px]">{t.nav.timeLogs}</span>
            </button>
            {isAdmin && (
              <button onClick={() => navigateTo('billing')} className={`flex flex-col items-center ${screen === 'billing' ? 'text-primary' : 'text-slate-400'}`}>
                <span className="material-icons">payments</span>
                <span className="text-[10px]">{t.nav.billing}</span>
              </button>
            )}
          </div>
        </nav>
      )}
    </div>
  );
};

export default App;
