'use client';

import React, { useEffect, useState, useCallback } from 'react';
import { useTranslation } from '@/lib/i18n';
import {
  Settings,
  Bell,
  BarChart3,
  Bot,
  Globe,
  Save,
  RefreshCw,
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Separator } from '@/components/ui/separator';
import { Badge } from '@/components/ui/badge';
import { Textarea } from '@/components/ui/textarea';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { authFetch } from '@/lib/api';

interface SettingItem {
  key: string;
  value: string | boolean | number;
  type: 'text' | 'number' | 'boolean' | 'textarea';
  label: string;
  description?: string;
}

interface SettingCategory {
  id: string;
  label: string;
  icon: React.ElementType;
  settings: SettingItem[];
}

const defaultCategories: SettingCategory[] = [
  {
    id: 'general',
    label: 'General',
    icon: Settings,
    settings: [
      { key: 'appName', value: 'Universal Support Desk', type: 'text', label: 'Application Name' },
      { key: 'appTagline', value: 'Streamlined complaint management', type: 'text', label: 'Tagline' },
      { key: 'defaultLanguage', value: 'en', type: 'text', label: 'Default Language', description: 'en or bn' },
      { key: 'maxFileUploadSize', value: 10, type: 'number', label: 'Max File Upload Size (MB)' },
      { key: 'maintenanceMode', value: false, type: 'boolean', label: 'Maintenance Mode' },
      { key: 'allowRegistration', value: true, type: 'boolean', label: 'Allow User Registration' },
    ],
  },
  {
    id: 'notification',
    label: 'Notifications',
    icon: Bell,
    settings: [
      { key: 'enableInAppNotifications', value: true, type: 'boolean', label: 'In-App Notifications' },
      { key: 'enableEmailNotifications', value: true, type: 'boolean', label: 'Email Notifications' },
      { key: 'enableWhatsappNotifications', value: false, type: 'boolean', label: 'WhatsApp Notifications' },
      { key: 'enableSmsNotifications', value: false, type: 'boolean', label: 'SMS Notifications' },
      { key: 'notificationEmailFrom', value: 'support@usd.com', type: 'text', label: 'From Email Address' },
      { key: 'whatsappApiToken', value: '', type: 'text', label: 'WhatsApp API Token' },
    ],
  },
  {
    id: 'workload',
    label: 'Workload',
    icon: BarChart3,
    settings: [
      { key: 'globalWorkloadLimit', value: 10, type: 'number', label: 'Global Workload Limit' },
      { key: 'autoAssign', value: true, type: 'boolean', label: 'Auto-Assign Complaints' },
      { key: 'balanceThreshold', value: 3, type: 'number', label: 'Balance Threshold' },
      { key: 'overdueHours', value: 48, type: 'number', label: 'Overdue After (Hours)' },
      { key: 'autoEscalate', value: true, type: 'boolean', label: 'Auto-Escalate Overdue' },
    ],
  },
  {
    id: 'ai',
    label: 'AI',
    icon: Bot,
    settings: [
      { key: 'enableAiAssistant', value: true, type: 'boolean', label: 'Enable AI Assistant' },
      { key: 'aiModel', value: 'default', type: 'text', label: 'AI Model' },
      { key: 'aiTemperature', value: 0.7, type: 'number', label: 'Temperature (0-1)' },
      { key: 'aiSystemPrompt', value: 'You are a helpful assistant for Universal Support Desk.', type: 'textarea', label: 'System Prompt' },
      { key: 'enableVoiceInput', value: true, type: 'boolean', label: 'Enable Voice Input' },
      { key: 'enableTextToSpeech', value: false, type: 'boolean', label: 'Enable Text-to-Speech' },
    ],
  },
  {
    id: 'portal',
    label: 'Portal',
    icon: Globe,
    settings: [
      { key: 'portalName', value: 'Universal Support Desk', type: 'text', label: 'Portal Name' },
      { key: 'supportEmail', value: 'support@usd.com', type: 'text', label: 'Support Email' },
      { key: 'supportPhone', value: '+880 1234-567890', type: 'text', label: 'Support Phone' },
      { key: 'showTicketTracking', value: true, type: 'boolean', label: 'Show Ticket Tracking' },
      { key: 'allowComplaintRating', value: true, type: 'boolean', label: 'Allow Complaint Rating' },
      { key: 'portalWelcomeMessage', value: 'Welcome to Universal Support Desk. We are here to help you resolve your complaints efficiently.', type: 'textarea', label: 'Welcome Message' },
    ],
  },
];

export default function DynamicSettings() {
  const { t } = useTranslation();
  const [categories, setCategories] = useState<SettingCategory[]>(defaultCategories);
  const [activeCategory, setActiveCategory] = useState('general');
  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(true);

  const fetchSettings = useCallback(async () => {
    setLoading(true);
    try {
      const res = await authFetch('/api/settings');
      if (res.ok) {
        const data = await res.json();
        const allSettings = data.settings || {};

        // Merge saved settings into categories
        setCategories((prev) =>
          prev.map((cat) => ({
            ...cat,
            settings: cat.settings.map((s) => {
              const catSettings = allSettings[cat.id] || {};
              const savedValue = catSettings[s.key];
              if (savedValue !== undefined) {
                return { ...s, value: savedValue };
              }
              return s;
            }),
          }))
        );
      }
    } catch (err) {
      console.error('Fetch settings error:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchSettings();
  }, [fetchSettings]);

  const updateSetting = (categoryId: string, key: string, value: string | boolean | number) => {
    setCategories((prev) =>
      prev.map((cat) =>
        cat.id === categoryId
          ? {
              ...cat,
              settings: cat.settings.map((s) =>
                s.key === key ? { ...s, value } : s
              ),
            }
          : cat
      )
    );
  };

  const saveSettings = async () => {
    setSaving(true);
    try {
      const settingsToSave = categories.flatMap((cat) =>
        cat.settings.map((s) => ({
          key: s.key,
          value: String(s.value),
          category: cat.id,
        }))
      );

      await authFetch('/api/settings', {
        method: 'PUT',
        body: JSON.stringify({ settings: settingsToSave }),
      });
    } catch (err) {
      console.error('Save settings error:', err);
    } finally {
      setSaving(false);
    }
  };

  const activeCat = categories.find((c) => c.id === activeCategory) || categories[0];
  const ActiveIcon = activeCat.icon;

  return (
    <div className="space-y-6 animate-fade-in">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        <div>
          <h1 className="text-2xl font-bold">{t.nav.settings}</h1>
          <p className="text-sm text-muted-foreground">Configure system settings and preferences</p>
        </div>
        <Button onClick={saveSettings} disabled={saving} className="bg-emerald-600 hover:bg-emerald-700">
          {saving ? <RefreshCw className="w-4 h-4 mr-2 animate-spin" /> : <Save className="w-4 h-4 mr-2" />}
          {saving ? t.common.loading : t.actions.save}
        </Button>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-4">
        {/* Category Tabs - Left */}
        <Card className="lg:col-span-1">
          <CardContent className="p-2">
            <nav className="space-y-0.5">
              {categories.map((cat) => {
                const CatIcon = cat.icon;
                return (
                  <button
                    key={cat.id}
                    onClick={() => setActiveCategory(cat.id)}
                    className={`w-full flex items-center gap-2.5 px-3 py-2.5 rounded-lg text-sm transition-all ${
                      activeCategory === cat.id
                        ? 'bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300 font-medium'
                        : 'text-muted-foreground hover:bg-accent/50 hover:text-foreground'
                    }`}
                  >
                    <CatIcon className="w-4 h-4 flex-shrink-0" />
                    <span>{cat.label}</span>
                    <Badge variant="outline" className="ml-auto text-[9px]">
                      {cat.settings.length}
                    </Badge>
                  </button>
                );
              })}
            </nav>
          </CardContent>
        </Card>

        {/* Settings - Right */}
        <Card className="lg:col-span-3">
          <CardHeader className="pb-3">
            <CardTitle className="text-base flex items-center gap-2">
              <ActiveIcon className="w-4 h-4 text-emerald-600" />
              {activeCat.label} Settings
            </CardTitle>
            <CardDescription>{activeCat.settings.length} configuration options</CardDescription>
          </CardHeader>
          <CardContent>
            {loading ? (
              <div className="p-8 text-center text-muted-foreground">{t.common.loading}</div>
            ) : (
              <div className="space-y-5">
                {activeCat.settings.map((setting, idx) => (
                  <div key={setting.key}>
                    {idx > 0 && <Separator className="mb-5" />}
                    <div className="space-y-2">
                      {setting.type === 'boolean' ? (
                        <div className="flex items-center justify-between">
                          <div>
                            <Label className="text-sm">{setting.label}</Label>
                            {setting.description && (
                              <p className="text-xs text-muted-foreground mt-0.5">{setting.description}</p>
                            )}
                          </div>
                          <Switch
                            checked={setting.value as boolean}
                            onCheckedChange={(v) => updateSetting(activeCat.id, setting.key, v)}
                          />
                        </div>
                      ) : setting.type === 'textarea' ? (
                        <div className="space-y-1.5">
                          <Label className="text-sm">{setting.label}</Label>
                          <Textarea
                            value={String(setting.value)}
                            onChange={(e) => updateSetting(activeCat.id, setting.key, e.target.value)}
                            rows={3}
                            className="text-sm"
                          />
                        </div>
                      ) : setting.type === 'number' ? (
                        <div className="space-y-1.5">
                          <Label className="text-sm">{setting.label}</Label>
                          <Input
                            type="number"
                            value={Number(setting.value)}
                            onChange={(e) => updateSetting(activeCat.id, setting.key, parseFloat(e.target.value) || 0)}
                            className="max-w-[200px]"
                          />
                          {setting.description && (
                            <p className="text-xs text-muted-foreground">{setting.description}</p>
                          )}
                        </div>
                      ) : (
                        <div className="space-y-1.5">
                          <Label className="text-sm">{setting.label}</Label>
                          <Input
                            type="text"
                            value={String(setting.value)}
                            onChange={(e) => updateSetting(activeCat.id, setting.key, e.target.value)}
                          />
                          {setting.description && (
                            <p className="text-xs text-muted-foreground">{setting.description}</p>
                          )}
                        </div>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
