import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery, useMutation } from '@tanstack/react-query';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Globe, Tag, Plus, Edit, Trash2, Layers, User as UserIcon, ShieldCheck, Share2, Server, Copy, Settings as SettingsIcon, Bell, Loader2, Clock } from 'lucide-react';
import { Switch } from '@/components/ui/switch';
import { ShareAccessModal } from '@/components/ShareAccessModal';
import { ChangePasswordModal } from '@/components/ChangePasswordModal';
import { UpdateProfileModal } from '@/components/UpdateProfileModal';
import { ShareLabelModal } from '@/components/ShareLabelModal';
import { Label } from '@shared/schema';
import { User } from '@shared/schema';
import { queryClient, apiRequest } from '@/lib/queryClient';
import { useToast } from '@/hooks/use-toast';
import { useLocation } from "wouter";
import { useNotifications } from '@/hooks/use-notifications';
import { DataExportCard } from '@/components/user/DataExportCard';

const NotificationSettings = () => {
  const { t } = useTranslation();
  const { toast } = useToast();
  const {
    enabled,
    toggleEnabled,
    permission,
    requestPermission,
    pushSupported,
    isStandalone,
    sendTestNotification,
    isLoading
  } = useNotifications({ poll: false });

  const handleToggle = async (checked: boolean) => {
    if (checked && permission !== 'granted') {
      const success = await requestPermission();
      if (success) {
        toast({
          title: t('notifications.enabledTitle'),
          description: t('notifications.enabledBody'),
        });
      }
    } else {
      await toggleEnabled(checked);
    }
  };

  const handleTestNotification = async () => {
    const success = await sendTestNotification();
    if (success) {
      toast({
        title: t('notifications.testSent', 'Test Sent'),
        description: t('notifications.testSentDesc', 'Check for a notification on your device.'),
      });
    } else {
      toast({
        title: t('common.error'),
        description: t('notifications.testFailed', 'Failed to send test notification.'),
        variant: 'destructive',
      });
    }
  };

  return (
    <div className="space-y-4">
      {/* Push Support Status */}
      {pushSupported && (
        <div className="flex items-center gap-2 text-sm">
          <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400">
            {t('notifications.pushSupported', 'Push Supported')}
          </span>
          {isStandalone && (
            <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-violet-100 text-violet-800 dark:bg-violet-900/30 dark:text-violet-400">
              {t('notifications.installedApp', 'Installed App')}
            </span>
          )}
        </div>
      )}

      {/* iOS PWA Hint */}
      {!pushSupported && /iPhone|iPad|iPod/.test(navigator.userAgent) && !isStandalone && (
        <div className="p-3 rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800">
          <p className="text-sm text-amber-800 dark:text-amber-200">
            <strong>{t('notifications.iosHintTitle', 'Add to Home Screen')}</strong><br />
            {t('notifications.iosHintDesc', 'To receive push notifications on iOS, tap the Share button and select "Add to Home Screen", then open the app from there.')}
          </p>
        </div>
      )}

      {/* Main Toggle */}
      <div className="flex items-center justify-between">
        <div className="space-y-0.5">
          <p className="font-medium">
            {pushSupported
              ? t('notifications.enablePush', 'Push Notifications')
              : t('notifications.enableBrowser')}
          </p>
          <p className="text-sm text-muted-foreground">
            {permission === 'denied' ? (
              <span className="text-destructive">
                {t('notifications.permissionDenied', 'Permission denied by browser. Please reset site permissions.')}
              </span>
            ) : pushSupported ? (
              t('notifications.pushDescription', 'Receive notifications even when the app is closed.')
            ) : (
              t('notifications.description')
            )}
          </p>
        </div>
        <Switch
          checked={enabled}
          onCheckedChange={handleToggle}
          disabled={permission === 'denied' || isLoading}
        />
      </div>

      {/* Test Button */}
      {enabled && pushSupported && (
        <Button
          variant="outline"
          size="sm"
          onClick={handleTestNotification}
          disabled={isLoading}
          className="w-full sm:w-auto"
        >
          {t('notifications.sendTest', 'Send Test Notification')}
        </Button>
      )}
    </div>
  );
};

const ScheduleSettings = ({ user }: { user: User }) => {
  const { t } = useTranslation();
  const { toast } = useToast();
  const [activeTab, setActiveTab] = useState<'work' | 'personal'>('work');

  // Helper to safely get availability data
  const getAvailability = (type: 'work' | 'personal') => {
    // Cast to any because TS might not know about the JSON structure fully yet if types aren't perfectly synced in IDE
    const avail = user.availability as any;
    if (avail && avail[type]) {
      return avail[type];
    }
    // Fallback defaults
    if (type === 'work') return user.workHours || { start: "09:00", end: "17:00", days: [1, 2, 3, 4, 5] };
    return { start: "18:00", end: "22:00", days: [1, 2, 3, 4, 5, 0, 6] };
  };

  // State for both schedules
  const [workSchedule, setWorkSchedule] = useState(getAvailability('work'));
  const [personalSchedule, setPersonalSchedule] = useState(getAvailability('personal'));

  const currentSchedule = activeTab === 'work' ? workSchedule : personalSchedule;
  const setCurrentSchedule = (newSched: any) => {
    if (activeTab === 'work') setWorkSchedule(newSched);
    else setPersonalSchedule(newSched);
  };

  const updateScheduleMutation = useMutation({
    mutationFn: async () => {
      const payload = {
        availability: {
          work: workSchedule,
          personal: personalSchedule
        }
      };
      const res = await apiRequest("PATCH", "/api/user/schedule", payload);
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/user"] });
      toast({ title: t('settings.schedule.saved') });
    }
  });

  const toggleDay = (day: number) => {
    const currentDays = currentSchedule.days || [];
    let newDays;
    if (currentDays.includes(day)) {
      newDays = currentDays.filter((d: number) => d !== day);
    } else {
      newDays = [...currentDays, day].sort();
    }
    setCurrentSchedule({ ...currentSchedule, days: newDays });
  };

  const handleChange = (field: 'start' | 'end', value: string) => {
    setCurrentSchedule({ ...currentSchedule, [field]: value });
  };

  const handleSave = () => {
    updateScheduleMutation.mutate();
  };

  const days = [
    { id: 1, label: t('analytics.mon') },
    { id: 2, label: t('analytics.tue') },
    { id: 3, label: t('analytics.wed') },
    { id: 4, label: t('analytics.thu') },
    { id: 5, label: t('analytics.fri') },
    { id: 6, label: t('analytics.sat') },
    { id: 0, label: t('analytics.sun') },
  ];

  return (
    <div className="space-y-6">
      <div className="flex space-x-4 border-b">
        <button
          className={`py-2 text-sm font-medium border-b-2 transition-colors ${activeTab === 'work' ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground'}`}
          onClick={() => setActiveTab('work')}
        >
          {t('settings.schedule.work', 'Work Schedule')}
        </button>
        <button
          className={`py-2 text-sm font-medium border-b-2 transition-colors ${activeTab === 'personal' ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground'}`}
          onClick={() => setActiveTab('personal')}
        >
          {t('settings.schedule.personal', 'Personal Schedule')}
        </button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div className="space-y-2">
          <label className="text-sm font-medium">{t('settings.schedule.start')}</label>
          <Input type="time" value={currentSchedule.start} onChange={(e) => handleChange('start', e.target.value)} />
        </div>
        <div className="space-y-2">
          <label className="text-sm font-medium">{t('settings.schedule.end')}</label>
          <Input type="time" value={currentSchedule.end} onChange={(e) => handleChange('end', e.target.value)} />
        </div>
      </div>

      <div className="space-y-2">
        <label className="text-sm font-medium">{t('settings.schedule.days')}</label>
        <div className="flex flex-wrap gap-2">
          {days.map(day => (
            <Button
              key={day.id}
              variant={currentSchedule.days?.includes(day.id) ? "default" : "outline"}
              size="sm"
              onClick={() => toggleDay(day.id)}
              className="w-12 h-12 rounded-full p-0"
            >
              {day.label.slice(0, 2)}
            </Button>
          ))}
        </div>
      </div>

      <div className="bg-muted/50 p-4 rounded-md text-sm text-muted-foreground">
        {activeTab === 'work'
          ? t('settings.schedule.workDesc', "Tasks with 'Work' labels will be scheduled during these hours.")
          : t('settings.schedule.personalDesc', "Tasks with 'Personal' labels will be scheduled during these hours. 'Neutral' tasks can use either.")}
      </div>

      <Button onClick={handleSave} disabled={updateScheduleMutation.isPending}>
        {updateScheduleMutation.isPending ? t('common.loading') : t('common.save')}
      </Button>
    </div>
  );
};

interface SettingsProps {
  onNavigateToTemplates: () => void;
}

export default function Settings({ onNavigateToTemplates }: SettingsProps) {
  const { t, i18n } = useTranslation();
  const { toast } = useToast();
  const [, setLocation] = useLocation();

  // Fetch user
  const { data: user, isLoading: isLoadingUser } = useQuery<User>({
    queryKey: ['/api/user']
  });

  if (isLoadingUser) {
    return (
      <div className="flex items-center justify-center min-h-[50vh]">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  if (!user) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[50vh] space-y-4">
        <h2 className="text-2xl font-bold">{t('common.loginRequired')}</h2>
        <Button onClick={() => setLocation('/')}>
          {t('auth.login')}
        </Button>
      </div>
    );
  }

  const [isLabelDialogOpen, setIsLabelDialogOpen] = useState(false);
  const [editingLabel, setEditingLabel] = useState<Label | null>(null);
  const [labelName, setLabelName] = useState('');
  const [labelColor, setLabelColor] = useState('#3B82F6');
  const [labelDomain, setLabelDomain] = useState('neutral');
  const [isShareAccessOpen, setIsShareAccessOpen] = useState(false);
  const [isShareLabelOpen, setIsShareLabelOpen] = useState(false);
  const [sharingLabel, setSharingLabel] = useState<Label | null>(null);
  const [isChangePasswordOpen, setIsChangePasswordOpen] = useState(false);
  const [isUpdateProfileOpen, setIsUpdateProfileOpen] = useState(false);

  const handleLanguageChange = (value: string) => {
    i18n.changeLanguage(value);
    localStorage.setItem('taskflow-language', value);
    // Persist to DB
    privacyMutation.mutate({ language: value } as any);
    console.log('Language changed to:', value);
  };

  const privacyMutation = useMutation({
    mutationFn: async (updates: { showOnLeaderboard?: boolean; isSearchable?: boolean; aiEnabled?: boolean }) => {
      const res = await apiRequest("PATCH", "/api/user/privacy", updates);
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/user"] });
      toast({ title: "Settings updated" });
    },
  });

  const handlePrivacyUpdate = (updates: { showOnLeaderboard?: boolean; isSearchable?: boolean; aiEnabled?: boolean }) => {
    privacyMutation.mutate(updates);
  };

  // 2FA Logic
  const [is2FADialogOpen, setIs2FADialogOpen] = useState(false);
  const [otpCode, setOtpCode] = useState("");
  const [debugCode, setDebugCode] = useState<string | null>(null);

  const generate2FAMutation = useMutation({
    mutationFn: async () => {
      const res = await apiRequest("POST", "/api/auth/2fa/generate");
      return res.json();
    },
    onSuccess: (data) => {
      setDebugCode(data.debugCode); // For dev convenience
      setIs2FADialogOpen(true);
      toast({ title: t('auth.2faCodeSent'), description: t('auth.checkEmail') });
    },
    onError: (err: Error) => {
      toast({ title: "Failed to start 2FA setup", description: err.message, variant: "destructive" });
    }
  });

  const verify2FAMutation = useMutation({
    mutationFn: async (code: string) => {
      const res = await apiRequest("POST", "/api/auth/verify-2fa", { userId: user.id, code });
      return res.json();
    },
    onSuccess: () => {
      setIs2FADialogOpen(false);
      setOtpCode("");
      queryClient.invalidateQueries({ queryKey: ["/api/user"] });
      toast({ title: "2FA Enabled Successfully" });
    },
    onError: (err: Error) => {
      toast({ title: "Verification failed", description: err.message, variant: "destructive" });
    }
  });

  const disable2FAMutation = useMutation({
    mutationFn: async () => {
      await apiRequest("POST", "/api/auth/2fa/disable");
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/user"] });
      toast({ title: "2FA Disabled" });
    }
  });

  const handle2FAToggle = (checked: boolean) => {
    if (checked) {
      generate2FAMutation.mutate(); // Starts flow, opens dialog on success
    } else {
      if (confirm("Are you sure you want to disable 2FA? This will reduce your account security.")) {
        disable2FAMutation.mutate();
      }
    }
  };


  // Fetch labels
  const { data: labelsData, isLoading: labelsLoading } = useQuery<Label[]>({
    queryKey: ['/api/labels']
  });
  const labels = labelsData ?? [];

  // Create label mutation
  const createLabelMutation = useMutation({
    mutationFn: (data: { name: string; color: string; domain: string }) =>
      apiRequest('POST', '/api/labels', data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/labels'] });
      setIsLabelDialogOpen(false);
      setLabelName('');
      setLabelColor('#3B82F6');
      setLabelDomain('neutral');
      toast({
        title: t('settings.labels.created'),
        description: t('settings.labels.createdDescription'),
      });
    },
  });

  // Update label mutation
  const updateLabelMutation = useMutation({
    mutationFn: ({ id, ...data }: { id: string; name: string; color: string; domain: string }) =>
      apiRequest('PATCH', `/api/labels/${id}`, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/labels'] });
      setIsLabelDialogOpen(false);
      setEditingLabel(null);
      setLabelName('');
      setLabelColor('#3B82F6');
      setLabelDomain('neutral');
      toast({
        title: t('settings.labels.updated'),
        description: t('settings.labels.updatedDescription'),
      });
    },
  });

  // Delete label mutation
  const deleteLabelMutation = useMutation({
    mutationFn: (id: string) => apiRequest('DELETE', `/api/labels/${id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/labels'] });
      toast({
        title: t('settings.labels.deleted'),
        description: t('settings.labels.deletedDescription'),
      });
    },
  });

  const handleSaveLabel = () => {
    if (!labelName.trim()) return;

    if (editingLabel) {
      updateLabelMutation.mutate({
        id: editingLabel.id,
        name: labelName,
        color: labelColor,
        domain: labelDomain,
      });
    } else {
      createLabelMutation.mutate({ name: labelName, color: labelColor, domain: labelDomain });
    }
  };

  const handleEditLabel = (label: Label) => {
    setEditingLabel(label);
    setLabelName(label.name);
    setLabelColor(label.color);
    setLabelDomain(label.domain || 'neutral');
    setIsLabelDialogOpen(true);
  };

  const handleDeleteLabel = (id: string) => {
    if (confirm(t('settings.labels.deleteConfirm'))) {
      deleteLabelMutation.mutate(id);
    }
  };

  const handleShareLabel = (label: Label) => {
    setSharingLabel(label);
    setIsShareLabelOpen(true);
  };

  const generateApiKeyMutation = useMutation({
    mutationFn: async () => {
      const res = await apiRequest("POST", "/api/user/apikey", {});
      return res.json();
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ["/api/user"] });
      toast({ title: t('settings.mcp.generated') });
    },
  });

  const revokeApiKeyMutation = useMutation({
    mutationFn: async () => {
      await apiRequest("DELETE", "/api/user/apikey");
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/user"] });
      toast({ title: t('settings.mcp.revoked') });
    },
  });

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    toast({ title: "Copied!" });
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold" data-testid="text-settings-title">
          {t('settings.title')}
        </h1>
      </div>

      {/* Account Settings */}
      <Card data-testid="card-account-settings">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <UserIcon className="w-5 h-5" />
            {t('settings.account.title')}
          </CardTitle>
          <CardDescription>
            {t('settings.account.description')}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-1">
            <p className="text-sm font-medium leading-none">{t('settings.account.username')}</p>
            <p className="text-sm text-muted-foreground">{user?.username || t('common.loading')}</p>
          </div>

          <div className="space-y-1" data-testid="container-email">
            <p className="text-sm font-medium leading-none">{t('auth.email')}</p>
            <div className="flex items-center gap-2">
              <p className="text-sm text-muted-foreground" data-testid="text-email">{user?.email || 'No email set'}</p>
              <Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => setIsUpdateProfileOpen(true)} data-testid="button-edit-email">
                <Edit className="h-3 w-3" />
              </Button>
            </div>
          </div>

          {user?.role === 'admin' && (
            <div className="space-y-1">
              <p className="text-sm font-medium leading-none">{t('settings.account.userId')}</p>
              <p className="text-sm text-muted-foreground font-mono">{user?.id || '...'}</p>
            </div>
          )}

          <div className="pt-2">
            <Button variant="outline" onClick={() => setIsChangePasswordOpen(true)} data-testid="button-change-password">
              {t('auth.changePassword')}
            </Button>
          </div>
        </CardContent>
      </Card>

      {user && (
        <>
          <UpdateProfileModal open={isUpdateProfileOpen} onOpenChange={setIsUpdateProfileOpen} user={user} />
          <ChangePasswordModal open={isChangePasswordOpen} onOpenChange={setIsChangePasswordOpen} />
        </>
      )}

      {/* Notifications Settings */}
      <Card data-testid="card-notifications">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Bell className="w-5 h-5" />
            {t('notifications.title')}
          </CardTitle>
          <CardDescription>
            {t('notifications.description')}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <NotificationSettings />
        </CardContent>
      </Card>

      {/* Social & Privacy */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <UserIcon className="w-5 h-5" />
            {t('settings.social.title')}
          </CardTitle>
          <CardDescription>
            {t('settings.social.description')}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center justify-between">
            <div className="space-y-0.5">
              <p className="font-medium">{t('settings.social.publicLeaderboard')}</p>
              <p className="text-sm text-muted-foreground">{t('settings.social.publicLeaderboardDesc')}</p>
            </div>
            <Switch
              checked={!!user?.showOnLeaderboard}
              onCheckedChange={(checked) => handlePrivacyUpdate({ showOnLeaderboard: checked })}
            />
          </div>
          <div className="flex items-center justify-between">
            <div className="space-y-0.5">
              <p className="font-medium">{t('settings.social.searchable')}</p>
              <p className="text-sm text-muted-foreground">{t('settings.social.searchableDesc')}</p>
            </div>
            <Switch
              checked={!!user?.isSearchable}
              onCheckedChange={(checked) => handlePrivacyUpdate({ isSearchable: checked })}
            />
          </div>
          <div className="flex items-center justify-between">
            <div className="space-y-0.5">
              <p className="font-medium">{t('settings.ai.enableUser')}</p>
              <p className="text-sm text-muted-foreground">{t('settings.ai.enableUserDesc')}</p>
            </div>
            <Switch
              checked={!!user?.aiEnabled}
              onCheckedChange={(checked) => handlePrivacyUpdate({ aiEnabled: checked })}
            />
          </div>
          <div className="flex items-center justify-between">
            <div className="space-y-0.5">
              <p className="font-medium">{t('settings.social.2fa')}</p>
              <p className="text-sm text-muted-foreground">{t('settings.social.2faDesc')}</p>
            </div>
            <Switch
              checked={!!user?.is2faEnabled}
              onCheckedChange={(checked) => handle2FAToggle(checked)}
              disabled={generate2FAMutation.isPending || disable2FAMutation.isPending}
            />
          </div>

          <Dialog open={is2FADialogOpen} onOpenChange={setIs2FADialogOpen}>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>{t('auth.verify2FATitle', 'Verify 2FA')}</DialogTitle>
                <CardDescription>
                  Enter the code sent to your email to enable 2FA.
                  {debugCode && <div className="mt-2 p-2 bg-muted rounded text-xs font-mono">Debug Code: {debugCode}</div>}
                </CardDescription>
              </DialogHeader>
              <div className="space-y-4 py-4">
                <Input
                  placeholder="123456"
                  className="text-center text-2xl tracking-widest"
                  maxLength={6}
                  value={otpCode}
                  onChange={(e) => setOtpCode(e.target.value.replace(/\D/g, ''))}
                />
                <Button
                  className="w-full"
                  onClick={() => verify2FAMutation.mutate(otpCode)}
                  disabled={verify2FAMutation.isPending || otpCode.length !== 6}
                >
                  {verify2FAMutation.isPending ? "Verifying..." : "Verify & Enable"}
                </Button>
              </div>
            </DialogContent>
          </Dialog>

          <div className="pt-2">
            <Button variant="outline" onClick={() => setIsShareAccessOpen(true)}>
              <Share2 className="w-4 h-4 mr-2" />
              {t('settings.social.shareAccess')}
            </Button>
          </div>
        </CardContent>
      </Card>

      <ShareAccessModal open={isShareAccessOpen} onOpenChange={setIsShareAccessOpen} />

      {/* Schedule Settings */}
      <Card data-testid="card-schedule-settings">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Clock className="w-5 h-5" />
            {t('settings.schedule.title')}
          </CardTitle>
          <CardDescription>
            {t('settings.schedule.description')}
          </CardDescription>
        </CardHeader>
        <CardContent>
          {user && <ScheduleSettings user={user} />}
        </CardContent>
      </Card>





      {/* Language Settings */}
      <Card data-testid="card-language-settings">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Globe className="w-5 h-5" />
            {t('settings.language.title')}
          </CardTitle>
          <CardDescription>
            {t('settings.language.description')}
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Select value={i18n.language} onValueChange={handleLanguageChange}>
            <SelectTrigger className="w-full sm:w-64" data-testid="select-language">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="en" data-testid="option-language-en">
                {t('settings.language.english')}
              </SelectItem>
              <SelectItem value="de" data-testid="option-language-de">
                {t('settings.language.german')}
              </SelectItem>
            </SelectContent>
          </Select>
        </CardContent>
      </Card>

      {/* Labels Management */}
      <Card data-testid="card-labels-management">
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="flex items-center gap-2">
                <Tag className="w-5 h-5" />
                {t('settings.labels.title')}
              </CardTitle>
              <CardDescription>
                {t('settings.labels.description')}
              </CardDescription>
            </div>
            <Dialog open={isLabelDialogOpen} onOpenChange={setIsLabelDialogOpen}>
              <DialogTrigger asChild>
                <Button variant="outline" size="sm" data-testid="button-create-label">
                  <Plus className="w-4 h-4 mr-2" />
                  {t('settings.labels.createLabel')}
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>
                    {editingLabel ? t('settings.labels.editLabel') : t('settings.labels.createNewLabel')}
                  </DialogTitle>
                </DialogHeader>
                <div className="space-y-4">
                  <div>
                    <Input
                      placeholder={t('settings.labels.labelNamePlaceholder')}
                      value={labelName}
                      onChange={(e) => setLabelName(e.target.value)}
                      data-testid="input-label-name"
                    />
                  </div>
                  <div>
                    <div className="flex items-center gap-3">
                      <input
                        type="color"
                        value={labelColor}
                        onChange={(e) => setLabelColor(e.target.value)}
                        className="w-12 h-8 rounded border cursor-pointer"
                        data-testid="input-label-color"
                      />
                      <Input
                        value={labelColor}
                        onChange={(e) => setLabelColor(e.target.value)}
                        placeholder="#3B82F6"
                        className="flex-1"
                        data-testid="input-label-color-text"
                      />
                    </div>
                  </div>
                  <div>
                    <Select value={labelDomain} onValueChange={setLabelDomain}>
                      <SelectTrigger>
                        <SelectValue placeholder="Context (Domain)" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="work">Work</SelectItem>
                        <SelectItem value="personal">Personal</SelectItem>
                        <SelectItem value="neutral">Neutral</SelectItem>
                      </SelectContent>
                    </Select>
                    <p className="text-xs text-muted-foreground mt-1">Used for smart scheduling.</p>
                  </div>
                  <div className="flex gap-3 pt-2">
                    <Button
                      variant="outline"
                      onClick={() => {
                        setIsLabelDialogOpen(false);
                        setEditingLabel(null);
                        setLabelName('');
                        setLabelColor('#3B82F6');
                        setLabelDomain('neutral');
                      }}
                      className="flex-1"
                      data-testid="button-cancel-label"
                    >
                      {t('settings.labels.cancel')}
                    </Button>
                    <Button
                      onClick={handleSaveLabel}
                      disabled={!labelName.trim() || createLabelMutation.isPending || updateLabelMutation.isPending}
                      className="flex-1"
                      data-testid="button-save-label"
                    >
                      {editingLabel ? t('settings.labels.update') : t('settings.labels.create')}
                    </Button>
                  </div>
                </div>
              </DialogContent>
            </Dialog>
          </div>
        </CardHeader>
        <CardContent>
          {labelsLoading ? (
            <div className="flex items-center justify-center p-8">
              <div className="text-muted-foreground">{t('settings.labels.loading')}</div>
            </div>
          ) : (
            <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
              {labels.map((label) => (
                <Card
                  key={label.id}
                  className="p-4 hover-elevate active-elevate-2"
                  style={{ borderLeft: `4px solid ${label.color}` }}
                  data-testid={`label-${label.id}`}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div
                        className="w-4 h-4 rounded"
                        style={{ backgroundColor: label.color }}
                      />
                      <div className="flex flex-col">
                        <span className="font-medium text-sm" data-testid={`text-label-name-${label.id}`}>
                          {label.name}
                        </span>
                        <span className="text-xs text-muted-foreground capitalize">
                          {label.domain || 'neutral'}
                        </span>
                      </div>
                    </div>
                    <div className="flex items-center gap-1">
                      {label.creatorId === user?.id && (
                        <Button
                          variant="ghost"
                          size="icon"
                          className="w-6 h-6 text-muted-foreground hover:text-primary"
                          onClick={() => handleShareLabel(label)}
                          title={t('settings.labels.share')}
                        >
                          <Share2 className="w-3 h-3" />
                        </Button>
                      )}
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => handleEditLabel(label)}
                        className="w-6 h-6"
                        data-testid={`button-edit-${label.id}`}
                      >
                        <Edit className="w-3 h-3" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => handleDeleteLabel(label.id)}
                        className="w-6 h-6 text-destructive hover:text-destructive"
                        data-testid={`button-delete-${label.id}`}
                      >
                        <Trash2 className="w-3 h-3" />
                      </Button>
                    </div>
                  </div>
                </Card>
              ))}
              {labels.length === 0 && (
                <div className="col-span-full flex flex-col items-center justify-center p-8 text-center">
                  <Tag className="w-12 h-12 text-muted-foreground mb-4" />
                  <h3 className="font-medium text-muted-foreground mb-2">{t('settings.labels.noLabels')}</h3>
                  <p className="text-sm text-muted-foreground mb-4">
                    {t('settings.labels.noLabelsDescription')}
                  </p>
                  <Button
                    variant="outline"
                    onClick={() => setIsLabelDialogOpen(true)}
                    data-testid="button-create-first-label"
                  >
                    <Plus className="w-4 h-4 mr-2" />
                    {t('settings.labels.createLabel')}
                  </Button>
                </div>
              )}
            </div>
          )}
        </CardContent>
      </Card>

      <ShareLabelModal
        open={isShareLabelOpen}
        onOpenChange={setIsShareLabelOpen}
        label={sharingLabel}
        currentUser={user}
      />

      {/* Project Templates */}
      <Card data-testid="card-project-templates">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Layers className="w-5 h-5" />
            {t('settings.templates.title')}
          </CardTitle>
          <CardDescription>
            {t('settings.templates.description')}
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Button
            onClick={onNavigateToTemplates}
            data-testid="button-manage-templates"
          >
            <Layers className="w-4 h-4 mr-2" />
            {t('settings.templates.manageTemplates')}
          </Button>
        </CardContent>
      </Card>

      {/* Data Export */}
      <DataExportCard user={user} />

      {/* Admin Section */}
      {
        user?.role === 'admin' && (
          <Card className="border-destructive/20 bg-destructive/5">
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-destructive">
                <ShieldCheck className="w-5 h-5" />
                {t('settings.admin.title')}
              </CardTitle>
              <CardDescription>{t('settings.admin.description')}</CardDescription>
            </CardHeader>
            <CardContent className="flex flex-col sm:flex-row gap-4">
              <Button variant="outline" onClick={() => setLocation('/admin/users')}>
                <UserIcon className="w-4 h-4 mr-2" />
                {t('settings.admin.manageUsers')}
              </Button>
              <Button variant="outline" onClick={() => setLocation('/admin/settings')}>
                <SettingsIcon className="w-4 h-4 mr-2" />
                {t('settings.admin.systemSettings')}
              </Button>
            </CardContent>
          </Card>
        )
      }
    </div >
  );
}
