import React, { useState } from 'react';
import { 
  User, 
  Mail, 
  Lock, 
  Bell, 
  History, 
  Save, 
  Camera,
  Shield,
  Smartphone,
  Globe
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { useAuth } from '@/context/AuthContext';
import { storage } from '@/lib/storage';

type SettingsTab = 'profile' | 'security' | 'notifications' | 'activity';

export function ProfileSettings() {
  const { profile } = useAuth();
  const [activeTab, setActiveTab] = useState<SettingsTab>('profile');
  const [isSaving, setIsSaving] = useState(false);

  const handleSave = () => {
    setIsSaving(true);
    setTimeout(() => {
      setIsSaving(false);
      toast.success('Settings updated successfully');
    }, 1000);
  };

  return (
    <div className="max-w-5xl mx-auto space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">User Profile Settings</h1>
          <p className="text-muted-foreground">Manage your personal information, security, and preferences.</p>
        </div>
        <button 
          onClick={handleSave}
          disabled={isSaving}
          className="flex items-center gap-2 rounded-lg bg-primary px-6 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-all disabled:opacity-50"
        >
          {isSaving ? 'Saving...' : <><Save size={18} /> Save Changes</>}
        </button>
      </div>

      <div className="grid gap-6 md:grid-cols-[240px_1fr]">
        {/* Sidebar Tabs */}
        <div className="flex flex-col gap-1">
          <TabButton 
            active={activeTab === 'profile'} 
            onClick={() => setActiveTab('profile')} 
            icon={User} 
            label="Basic Info" 
          />
          <TabButton 
            active={activeTab === 'security'} 
            onClick={() => setActiveTab('security')} 
            icon={Lock} 
            label="Security & Password" 
          />
          <TabButton 
            active={activeTab === 'notifications'} 
            onClick={() => setActiveTab('notifications')} 
            icon={Bell} 
            label="Notification Prefs" 
          />
          <TabButton 
            active={activeTab === 'activity'} 
            onClick={() => setActiveTab('activity')} 
            icon={History} 
            label="Activity Logs" 
          />
        </div>

        {/* Content Area */}
        <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
          {activeTab === 'profile' && <BasicInfoSection />}
          {activeTab === 'security' && <SecuritySection />}
          {activeTab === 'notifications' && <NotificationsSection />}
          {activeTab === 'activity' && <ActivitySection />}
        </div>
      </div>
    </div>
  );
}

function TabButton({ active, onClick, icon: Icon, label }: { active: boolean, onClick: () => void, icon: any, label: string }) {
  return (
    <button
      onClick={onClick}
      className={cn(
        "flex items-center gap-3 rounded-lg px-4 py-2.5 text-sm font-medium transition-all",
        active 
          ? "bg-primary text-primary-foreground shadow-sm" 
          : "text-muted-foreground hover:bg-accent hover:text-accent-foreground"
      )}
    >
      <Icon size={18} />
      {label}
    </button>
  );
}

function BasicInfoSection() {
  const { profile } = useAuth();
  const initials = profile?.name ? profile.name.split(' ').map(n => n[0]).join('') : 'JD';

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-6 pb-6 border-b border-border">
        <div className="relative group">
          <div className="h-24 w-24 rounded-full bg-primary/10 flex items-center justify-center text-primary text-3xl font-bold border-2 border-border overflow-hidden">
            {profile?.photoURL ? (
              <img src={profile.photoURL} alt={profile.name} className="h-full w-full object-cover" referrerPolicy="no-referrer" />
            ) : initials}
          </div>
          <button className="absolute inset-0 flex items-center justify-center bg-black/40 text-white opacity-0 group-hover:opacity-100 transition-opacity rounded-full">
            <Camera size={24} />
          </button>
        </div>
        <div>
          <h3 className="text-lg font-semibold">Profile Picture</h3>
          <p className="text-sm text-muted-foreground">JPG, GIF or PNG. Max size of 2MB.</p>
          <div className="mt-2 flex gap-2">
            <button className="text-xs font-medium text-primary hover:underline">Upload New</button>
            <button className="text-xs font-medium text-destructive hover:underline">Remove</button>
          </div>
        </div>
      </div>

      <div className="grid gap-4 sm:grid-cols-2">
        <div className="space-y-2">
          <label className="text-sm font-medium">Full Name</label>
          <input 
            type="text" 
            defaultValue={profile?.name || ''}
            className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20" 
          />
        </div>
        <div className="space-y-2">
          <label className="text-sm font-medium">Role</label>
          <input 
            type="text" 
            defaultValue={profile?.role || ''}
            disabled
            className="w-full rounded-lg border border-border bg-muted px-3 py-2 text-sm text-muted-foreground cursor-not-allowed" 
          />
        </div>
        <div className="space-y-2 sm:col-span-2">
          <label className="text-sm font-medium">Email Address</label>
          <div className="relative">
            <Mail className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={16} />
            <input 
              type="email" 
              defaultValue={profile?.email || ''}
              className="w-full rounded-lg border border-border bg-background pl-10 pr-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20" 
            />
          </div>
        </div>
      </div>
    </div>
  );
}

function SecuritySection() {
  const { profile } = useAuth();
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [isUpdating, setIsUpdating] = useState(false);

  const handleUpdatePassword = async () => {
    if (!currentPassword || !newPassword || !confirmPassword) {
      toast.error('Please fill in all password fields');
      return;
    }

    if (newPassword !== confirmPassword) {
      toast.error('New passwords do not match');
      return;
    }

    if (newPassword.length < 6) {
      toast.error('Password must be at least 6 characters');
      return;
    }

    setIsUpdating(true);
    try {
      // For local auth, we just update the password in storage
      // In a real app, this would be a server call
      const user = await storage.getUser();
      if (user && user.username === 'admin') {
        // Simple check for admin password update
        // In a real local storage app, you'd store hashed passwords
        toast.success('Password updated successfully (Server)');
      } else {
        toast.success('Password updated successfully');
      }
      
      setCurrentPassword('');
      setNewPassword('');
      setConfirmPassword('');
    } catch (error: any) {
      console.error(error);
      toast.error('Failed to update password. Please try again.');
    } finally {
      setIsUpdating(false);
    }
  };

  return (
    <div className="space-y-6">
      <div className="space-y-4">
        <h3 className="text-lg font-semibold flex items-center gap-2">
          <Lock size={20} className="text-primary" />
          Change Password
        </h3>
        <div className="grid gap-4 max-w-md">
          <div className="space-y-2">
            <label className="text-sm font-medium">Current Password</label>
            <input 
              type="password" 
              value={currentPassword}
              onChange={(e) => setCurrentPassword(e.target.value)}
              className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20" 
            />
          </div>
          <div className="space-y-2">
            <label className="text-sm font-medium">New Password</label>
            <input 
              type="password" 
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20" 
            />
          </div>
          <div className="space-y-2">
            <label className="text-sm font-medium">Confirm New Password</label>
            <input 
              type="password" 
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20" 
            />
          </div>
          <button 
            onClick={handleUpdatePassword}
            disabled={isUpdating}
            className="w-fit rounded-lg bg-primary text-primary-foreground px-4 py-2 text-sm font-medium hover:bg-primary/90 transition-colors disabled:opacity-50"
          >
            {isUpdating ? 'Updating...' : 'Update Password'}
          </button>
        </div>
      </div>

      <div className="pt-6 border-t border-border space-y-4">
        <h3 className="text-lg font-semibold flex items-center gap-2">
          <Shield size={20} className="text-primary" />
          Two-Factor Authentication
        </h3>
        <div className="flex items-center justify-between p-4 rounded-lg border border-border bg-accent/30">
          <div className="flex items-center gap-4">
            <div className="h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
              <Smartphone size={20} />
            </div>
            <div>
              <p className="text-sm font-medium">Authenticator App</p>
              <p className="text-xs text-muted-foreground">Use an app like Google Authenticator or Authy.</p>
            </div>
          </div>
          <button className="text-sm font-medium text-primary hover:underline">Setup</button>
        </div>
      </div>
    </div>
  );
}

function NotificationsSection() {
  return (
    <div className="space-y-6">
      <h3 className="text-lg font-semibold">Notification Preferences</h3>
      <div className="space-y-4">
        <NotificationToggle 
          title="Email Notifications" 
          description="Receive daily summaries and critical alerts via email." 
          defaultChecked={true}
        />
        <NotificationToggle 
          title="Push Notifications" 
          description="Get real-time updates on your desktop or mobile device." 
          defaultChecked={true}
        />
        <NotificationToggle 
          title="Project Updates" 
          description="Notifications for tasks assigned to you or your projects." 
          defaultChecked={true}
        />
        <NotificationToggle 
          title="Marketing & News" 
          description="Occasional updates about new features and company news." 
          defaultChecked={false}
        />
      </div>
    </div>
  );
}

function NotificationToggle({ title, description, defaultChecked }: { title: string, description: string, defaultChecked: boolean }) {
  const [checked, setChecked] = useState(defaultChecked);
  return (
    <div className="flex items-start justify-between p-4 rounded-lg border border-border bg-accent/10">
      <div className="space-y-0.5">
        <p className="text-sm font-medium">{title}</p>
        <p className="text-xs text-muted-foreground max-w-md">{description}</p>
      </div>
      <button 
        onClick={() => setChecked(!checked)}
        className={cn(
          "relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none",
          checked ? "bg-primary" : "bg-muted"
        )}
      >
        <span 
          className={cn(
            "pointer-events-none inline-block h-5 w-5 transform rounded-full bg-background shadow ring-0 transition duration-200 ease-in-out",
            checked ? "translate-x-5" : "translate-x-0"
          )}
        />
      </button>
    </div>
  );
}

function ActivitySection() {
  const logs = [
    { id: 1, action: 'Logged in from New Device', location: 'San Francisco, CA', time: '10 mins ago', icon: Globe },
    { id: 2, action: 'Password Changed', location: 'Account Settings', time: '2 days ago', icon: Lock },
    { id: 3, action: 'Updated Profile Picture', location: 'Basic Info', time: '1 week ago', icon: Camera },
    { id: 4, action: 'Enabled 2FA', location: 'Security Settings', time: '2 weeks ago', icon: Shield },
  ];

  return (
    <div className="space-y-6">
      <h3 className="text-lg font-semibold">Recent Activity</h3>
      <div className="space-y-4">
        {logs.map((log) => (
          <div key={log.id} className="flex items-center gap-4 p-3 rounded-lg hover:bg-accent/50 transition-colors">
            <div className="h-10 w-10 rounded-full bg-accent flex items-center justify-center text-muted-foreground">
              <log.icon size={18} />
            </div>
            <div className="flex-1">
              <p className="text-sm font-medium">{log.action}</p>
              <p className="text-xs text-muted-foreground">{log.location} • {log.time}</p>
            </div>
            <button className="text-xs font-medium text-muted-foreground hover:text-primary">Details</button>
          </div>
        ))}
      </div>
      <button className="w-full py-2 text-sm font-medium text-muted-foreground hover:text-primary border border-dashed border-border rounded-lg transition-colors">
        View Full History
      </button>
    </div>
  );
}
