
import React, { useState, useEffect } from 'react';
import { Screen, UserProfile, Client, WorkLog, CompanyProfile } from '../types';
import { Language, translations } from '../i18n';

interface DashboardProps {
  navigateTo: (screen: Screen, clientId?: string) => void;
  language: Language;
  user: UserProfile | null;
  clients: Client[];
  workLogs: WorkLog[];
  allUsers?: UserProfile[];
  onAssign?: (staffId: string, clientId: string, lat: number, lng: number) => void;
  companyProfile: CompanyProfile;
}

const Dashboard: React.FC<DashboardProps> = ({ navigateTo, language, user, clients, workLogs, allUsers = [], onAssign, companyProfile }) => {
  const t = translations[language].dashboard;
  const [isClockedIn, setIsClockedIn] = useState(() => localStorage.getItem('is_clocked_in') === 'true');
  const [timer, setTimer] = useState(() => parseInt(localStorage.getItem('timer_seconds') || '0'));
  const [locationStatus, setLocationStatus] = useState<'idle' | 'verifying' | 'verified' | 'error'>('idle');
  const [locationError, setLocationError] = useState<string | null>(null);

  // Assignment Center States
  const [assignStaffId, setAssignStaffId] = useState('');
  const [assignClientId, setAssignClientId] = useState('');
  const [assignLat, setAssignLat] = useState('52.0907');
  const [assignLng, setAssignLng] = useState('5.1214');
  const [showSuccess, setShowSuccess] = useState(false);

  useEffect(() => {
    let interval: any;
    if (isClockedIn) {
      interval = setInterval(() => {
        setTimer(t => {
          const newVal = t + 1;
          localStorage.setItem('timer_seconds', newVal.toString());
          return newVal;
        });
      }, 1000);
    }
    localStorage.setItem('is_clocked_in', isClockedIn.toString());
    return () => clearInterval(interval);
  }, [isClockedIn]);

  useEffect(() => {
    if (assignClientId) {
      const selectedClient = clients.find(c => c.id === assignClientId);
      if (selectedClient && selectedClient.lat && selectedClient.lng) {
        setAssignLat(selectedClient.lat.toString());
        setAssignLng(selectedClient.lng.toString());
      }
    }
  }, [assignClientId, clients]);

  const calculateDistance = (lat1: number, lon1: number, lat2: number, lon2: number) => {
    const R = 6371;
    const dLat = (lat2 - lat1) * Math.PI / 180;
    const dLon = (lon2 - lon1) * Math.PI / 180;
    const a = 
      Math.sin(dLat/2) * Math.sin(dLat/2) +
      Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
      Math.sin(dLon/2) * Math.sin(dLon/2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    return R * c;
  };

  const handleToggleClock = async () => {
    if (!isClockedIn) {
      setLocationStatus('verifying');
      setLocationError(null);

      if (!navigator.geolocation) {
        setLocationStatus('error');
        setLocationError(t.locationRequired);
        return;
      }

      navigator.geolocation.getCurrentPosition(
        (position) => {
          const { latitude, longitude } = position.coords;
          const workLat = user?.workLat || 52.0907;
          const workLng = user?.workLng || 5.1214;
          const distance = calculateDistance(latitude, longitude, workLat, workLng);
          
          if (distance <= 0.2) {
            setLocationStatus('verified');
            setIsClockedIn(true);
          } else {
            setLocationStatus('error');
            setLocationError(t.locationTooFar);
          }
        },
        (error) => {
          console.error('Geolocation error:', error);
          setLocationStatus('error');
          setLocationError(t.enableGPS);
        },
        { enableHighAccuracy: true, timeout: 5000 }
      );
    } else {
      setIsClockedIn(false);
      setLocationStatus('idle');
      setLocationError(null);
    }
  };

  const handleSaveAssignment = () => {
    if (onAssign && assignStaffId && assignClientId) {
      onAssign(assignStaffId, assignClientId, parseFloat(assignLat), parseFloat(assignLng));
      setShowSuccess(true);
      setTimeout(() => setShowSuccess(false), 3000);
    }
  };

  const formatTime = (seconds: number) => {
    const h = Math.floor(seconds / 3600);
    const m = Math.floor((seconds % 3600) / 60);
    const s = seconds % 60;
    return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  };

  const initials = user?.fullName ? user.fullName.split(/\s+/).map(p => p[0]).join('').substring(0, 2).toUpperCase() : 'JD';
  const firstName = user?.fullName ? user.fullName.split(/\s+/)[0] : 'Professional';
  const userRole = user?.role || translations[language].profile.nurse;
  const isAdmin = user?.roleType === 'admin';

  const activeClientsCount = clients.length;
  const totalHoursThisWeek = workLogs.reduce((acc, log) => acc + log.hours, 0).toFixed(1);

  const selectedClient = clients.find(c => c.id === assignClientId);

  const quickActions = [
    { icon: 'person_add', label: t.actions.addClient, screen: 'add-client', color: 'bg-blue-50 text-blue-500', adminOnly: false },
    { icon: 'edit_note', label: t.actions.newReport, screen: 'new-report', color: 'bg-green-50 text-green-500', adminOnly: false },
    { icon: 'timer', label: t.actions.hours, screen: 'time-logs', color: 'bg-orange-50 text-orange-500', adminOnly: false },
    { icon: 'receipt_long', label: t.actions.billing, screen: 'billing', color: 'bg-purple-50 text-purple-500', adminOnly: true },
    { icon: 'group', label: translations[language].nav.staff, screen: 'staff', color: 'bg-teal-50 text-teal-500', adminOnly: true },
  ].filter(a => !a.adminOnly || isAdmin);

  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 safe-area-pt px-4 pb-4 border-b border-slate-300 dark:border-slate-800">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
             {companyProfile.logoUrl && (
               <img src={companyProfile.logoUrl} alt="Logo" className="w-8 h-8 rounded-lg object-contain" />
             )}
             <div>
               <h1 className="text-lg font-bold tracking-tight text-primary leading-tight">{companyProfile.name}</h1>
               <div className="flex flex-col">
                 <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest leading-tight">
                   {t.welcome}, {firstName}
                 </p>
               </div>
             </div>
          </div>
          <button 
            onClick={() => navigateTo('profile')} 
            className="w-10 h-10 rounded-full border-2 border-primary/20 bg-primary/10 flex items-center justify-center overflow-hidden transition-all active:scale-90 hover:border-primary"
          >
            <span className="text-xs font-bold text-primary">{initials}</span>
          </button>
        </div>
      </header>

      <main className="px-4 py-6 space-y-6 pb-24">
        {/* Clock In Section with Location Logic */}
        <section className={`p-6 rounded-3xl shadow-md transition-all duration-300 relative overflow-hidden ${
          isClockedIn ? 'bg-primary text-white shadow-primary/20' : 'bg-surface-light dark:bg-surface-dark text-slate-900 dark:text-white border border-slate-300 dark:border-slate-800'
        }`}>
          <div className="flex items-center justify-between relative z-10">
            <div>
              <p className={`text-[10px] uppercase font-black tracking-widest mb-1 ${isClockedIn ? 'opacity-70' : 'text-slate-400'}`}>
                {isClockedIn ? t.clockOut : t.clockIn}
              </p>
              <h2 className="text-4xl font-black font-mono tracking-tighter">{formatTime(timer)}</h2>
              
              {/* Location Status Badge */}
              <div className="mt-3 flex items-center gap-2">
                {locationStatus === 'verifying' && (
                  <span className="flex items-center gap-1 text-[10px] font-bold text-blue-500 animate-pulse">
                    <span className="material-icons text-xs">gps_fixed</span>
                    {t.locationVerifying}
                  </span>
                )}
                {locationStatus === 'verified' && (
                  <span className={`flex items-center gap-1 text-[10px] font-bold ${isClockedIn ? 'text-white' : 'text-green-500'}`}>
                    <span className="material-icons text-xs">verified</span>
                    {t.locationVerified}
                  </span>
                )}
                {locationStatus === 'error' && (
                  <span className="flex items-center gap-1 text-[10px] font-bold text-red-500">
                    <span className="material-icons text-xs">location_off</span>
                    {t.locationError}
                  </span>
                )}
              </div>
            </div>
            <button 
              onClick={handleToggleClock}
              disabled={locationStatus === 'verifying'}
              className={`w-16 h-16 rounded-full flex items-center justify-center shadow-lg transition-all active:scale-90 ${
                isClockedIn 
                  ? 'bg-red-500' 
                  : 'bg-primary text-white hover:brightness-110 disabled:opacity-50'
              }`}
            >
              <span className="material-icons text-3xl">
                {locationStatus === 'verifying' ? 'refresh' : isClockedIn ? 'stop' : 'play_arrow'}
              </span>
            </button>
          </div>

          {locationError && (
            <div className="mt-4 p-3 bg-red-100 dark:bg-red-900/30 rounded-xl border border-red-200 dark:border-red-900/50 flex gap-2 animate-in slide-in-from-top-2">
              <span className="material-icons text-red-500 text-sm">warning</span>
              <p className="text-[11px] font-bold text-red-700 dark:text-red-300 leading-tight">
                {locationError}
              </p>
            </div>
          )}
        </section>

        {/* Admin Assignment Center */}
        {isAdmin && (
          <section className="bg-surface-light dark:bg-surface-dark p-5 rounded-3xl shadow-sm border border-slate-300 dark:border-slate-800 space-y-4">
            <h2 className="text-[10px] font-bold uppercase tracking-widest text-primary flex items-center gap-2">
              <span className="material-icons text-sm">assignment_ind</span>
              {t.assignmentCenter}
            </h2>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-1.5">
                <label className="text-[10px] font-bold text-slate-400 uppercase tracking-tight ml-1">{t.selectStaff}</label>
                <select 
                  value={assignStaffId}
                  onChange={(e) => setAssignStaffId(e.target.value)}
                  className="w-full bg-slate-50 dark:bg-slate-900 border-none rounded-xl py-2.5 px-4 text-xs font-medium focus:ring-2 focus:ring-primary/40 transition-all"
                >
                  <option value="">-- {t.selectStaff} --</option>
                  {allUsers.filter(u => u.status === 'active').map(u => (
                    <option key={u.id} value={u.id}>{u.fullName} ({u.role || u.roleType})</option>
                  ))}
                </select>
              </div>
              
              <div className="space-y-1.5">
                <label className="text-[10px] font-bold text-slate-400 uppercase tracking-tight ml-1">{t.selectClient}</label>
                <select 
                  value={assignClientId}
                  onChange={(e) => setAssignClientId(e.target.value)}
                  className="w-full bg-slate-50 dark:bg-slate-900 border-none rounded-xl py-2.5 px-4 text-xs font-medium focus:ring-2 focus:ring-primary/40 transition-all"
                >
                  <option value="">-- {t.selectClient} --</option>
                  {clients.map(c => (
                    <option key={c.id} value={c.id}>{c.name}</option>
                  ))}
                </select>
              </div>
            </div>

            {selectedClient && (
              <div className="p-3 bg-healthcare-soft/30 dark:bg-slate-700/50 rounded-xl border border-primary/10 animate-in slide-in-from-top-1">
                <div className="flex items-center gap-2 mb-1">
                   <span className="material-icons text-primary text-sm">home</span>
                   <span className="text-[10px] font-bold uppercase tracking-wider text-primary">{t.clientLocationInfo}</span>
                </div>
                <p className="text-xs font-medium text-slate-600 dark:text-slate-300 ml-6">
                   {selectedClient.address || 'No address registered'}
                </p>
              </div>
            )}

            <div className="space-y-1.5 pt-2">
              <label className="text-[10px] font-bold text-slate-400 uppercase tracking-tight ml-1">{t.workLocation}</label>
              <div className="grid grid-cols-2 gap-3">
                <input 
                  type="number" 
                  step="0.0001"
                  value={assignLat}
                  onChange={(e) => setAssignLat(e.target.value)}
                  placeholder={t.latitude}
                  className="w-full bg-slate-50 dark:bg-slate-900 border-none rounded-xl py-2.5 px-4 text-xs font-mono focus:ring-2 focus:ring-primary/40 transition-all"
                />
                <input 
                  type="number" 
                  step="0.0001"
                  value={assignLng}
                  onChange={(e) => setAssignLng(e.target.value)}
                  placeholder={t.longitude}
                  className="w-full bg-slate-50 dark:bg-slate-900 border-none rounded-xl py-2.5 px-4 text-xs font-mono focus:ring-2 focus:ring-primary/40 transition-all"
                />
              </div>
            </div>

            <button 
              onClick={handleSaveAssignment}
              disabled={!assignStaffId || !assignClientId}
              className="w-full bg-primary text-white py-3 rounded-xl font-bold text-xs shadow-lg shadow-primary/20 active:scale-95 transition-all disabled:opacity-40 disabled:shadow-none"
            >
              {t.saveAssignment}
            </button>

            {showSuccess && (
              <p className="text-center text-[10px] font-bold text-green-500 uppercase animate-in fade-in">
                {t.assignmentSuccess}
              </p>
            )}
          </section>
        )}

        <section className="grid grid-cols-2 gap-4">
          <div className="bg-white dark:bg-slate-800 p-4 rounded-3xl shadow-sm border border-primary/5 active:bg-primary/5 transition-colors cursor-pointer" onClick={() => navigateTo('clients')}>
            <span className="material-icons text-primary bg-primary/10 p-2 rounded-xl mb-3">people</span>
            <div className="text-2xl font-black">{activeClientsCount}</div>
            <div className="text-[10px] text-slate-500 font-bold uppercase tracking-wider">{t.activeClients}</div>
          </div>
          <div className="bg-white dark:bg-slate-800 p-4 rounded-3xl shadow-sm border border-primary/5 active:bg-primary/5 transition-colors cursor-pointer" onClick={() => navigateTo('time-logs')}>
            <span className="material-icons text-purple-500 bg-purple-50 p-2 rounded-xl mb-3">timer</span>
            <div className="text-2xl font-black">{totalHoursThisWeek}h</div>
            <div className="text-[10px] text-slate-500 font-bold uppercase tracking-wider">{t.loggedHours}</div>
          </div>
        </section>

        <section className="bg-white dark:bg-slate-800 p-5 rounded-3xl shadow-sm border border-primary/5">
          <h2 className="text-[10px] font-bold mb-4 uppercase tracking-widest text-slate-400">{t.quickActions}</h2>
          <div className="grid grid-cols-4 gap-4">
            {quickActions.map((action, idx) => (
              <button 
                key={idx} 
                onClick={() => navigateTo(action.screen as any)}
                className="flex flex-col items-center gap-2"
              >
                <div className={`w-12 h-12 rounded-2xl ${action.color} flex items-center justify-center shadow-sm active:scale-90 transition-transform`}>
                  <span className="material-icons">{action.icon}</span>
                </div>
                <span className="text-[10px] font-bold text-slate-500 text-center leading-tight">{action.label}</span>
              </button>
            ))}
          </div>
        </section>
      </main>
    </div>
  );
};

export default Dashboard;
