'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from '@/lib/i18n';
import { useStore } from '@/lib/store';
import { Settings, Plus, Trash2, Edit3, Save, X, Loader2, AlertCircle } 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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { authFetch } from '@/lib/api';

interface SettingItem {
  id: string;
  key: string;
  value: string;
  category: string;
}

const COMPLAINT_TYPES = ['hardware', 'software', 'network', 'other'];
const PRIORITY_LEVELS = ['low', 'medium', 'high', 'critical'];
const STATUS_OPTIONS = ['pending', 'assigned', 'in_progress', 'diagnosed', 'resolved', 'closed'];

const SLA_DEFAULTS = [
  { key: 'sla_low_hours', value: '72', category: 'sla' },
  { key: 'sla_medium_hours', value: '48', category: 'sla' },
  { key: 'sla_high_hours', value: '24', category: 'sla' },
  { key: 'sla_critical_hours', value: '4', category: 'sla' },
];

const NOTIFICATION_TEMPLATES = [
  { key: 'notif_complaint_created', value: 'Your complaint {ticketNumber} has been created. We will assign it shortly.', category: 'notification_template' },
  { key: 'notif_complaint_assigned', value: 'Your complaint {ticketNumber} has been assigned to {engineerName}.', category: 'notification_template' },
  { key: 'notif_complaint_resolved', value: 'Your complaint {ticketNumber} has been resolved. Please confirm.', category: 'notification_template' },
  { key: 'notif_complaint_closed', value: 'Your complaint {ticketNumber} has been closed. Thank you!', category: 'notification_template' },
];

export default function MasterSettings() {
  const { t } = useTranslation();
  const { language } = useStore();
  const [settings, setSettings] = useState<SettingItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [activeTab, setActiveTab] = useState('complaint_types');

  // Editable state
  const [complaintTypes, setComplaintTypes] = useState<string[]>(COMPLAINT_TYPES);
  const [priorityLevels, setPriorityLevels] = useState<string[]>(PRIORITY_LEVELS);
  const [statusOptions, setStatusOptions] = useState<string[]>(STATUS_OPTIONS);
  const [slaSettings, setSlaSettings] = useState(SLA_DEFAULTS);
  const [notifTemplates, setNotifTemplates] = useState(NOTIFICATION_TEMPLATES);
  const [generalSettings, setGeneralSettings] = useState<SettingItem[]>([]);

  // Dialogs
  const [addDialogOpen, setAddDialogOpen] = useState(false);
  const [newItemName, setNewItemName] = useState('');
  const [addTarget, setAddTarget] = useState('');

  const fetchSettings = useCallback(async () => {
    setLoading(true);
    try {
      const res = await authFetch('/api/settings');
      if (res.ok) {
        const data = await res.json();
        const items: SettingItem[] = data.settings || [];
        setSettings(items);
        setGeneralSettings(items.filter(s => s.category === 'general'));

        // Load complaint types from settings if available
        const ct = items.find(s => s.key === 'complaint_types');
        if (ct) { try { setComplaintTypes(JSON.parse(ct.value)); } catch { /* keep defaults */ } }
        const pl = items.find(s => s.key === 'priority_levels');
        if (pl) { try { setPriorityLevels(JSON.parse(pl.value)); } catch { /* keep defaults */ } }
        const so = items.find(s => s.key === 'status_options');
        if (so) { try { setStatusOptions(JSON.parse(so.value)); } catch { /* keep defaults */ } }
        const sla = items.filter(s => s.category === 'sla');
        if (sla.length) setSlaSettings(sla);
        const nt = items.filter(s => s.category === 'notification_template');
        if (nt.length) setNotifTemplates(nt);
      }
    } catch { } finally { setLoading(false); }
  }, []);

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

  const saveSetting = async (key: string, value: string, category: string) => {
    setSaving(true);
    try {
      const res = await authFetch('/api/settings', {
        method: 'POST',
        body: JSON.stringify({ key, value, category }),
      });
      if (res.ok) fetchSettings();
    } catch { } finally { setSaving(false); }
  };

  const handleAddItem = () => {
    if (!newItemName.trim()) return;
    if (addTarget === 'complaint_types') {
      const updated = [...complaintTypes, newItemName.trim().toLowerCase().replace(/\s+/g, '_')];
      setComplaintTypes(updated);
      saveSetting('complaint_types', JSON.stringify(updated), 'general');
    } else if (addTarget === 'priority_levels') {
      const updated = [...priorityLevels, newItemName.trim().toLowerCase().replace(/\s+/g, '_')];
      setPriorityLevels(updated);
      saveSetting('priority_levels', JSON.stringify(updated), 'general');
    } else if (addTarget === 'status_options') {
      const updated = [...statusOptions, newItemName.trim().toLowerCase().replace(/\s+/g, '_')];
      setStatusOptions(updated);
      saveSetting('status_options', JSON.stringify(updated), 'general');
    }
    setNewItemName('');
    setAddDialogOpen(false);
  };

  const handleDeleteItem = (target: string, index: number) => {
    if (target === 'complaint_types') {
      const updated = complaintTypes.filter((_, i) => i !== index);
      setComplaintTypes(updated);
      saveSetting('complaint_types', JSON.stringify(updated), 'general');
    } else if (target === 'priority_levels') {
      const updated = priorityLevels.filter((_, i) => i !== index);
      setPriorityLevels(updated);
      saveSetting('priority_levels', JSON.stringify(updated), 'general');
    } else if (target === 'status_options') {
      const updated = statusOptions.filter((_, i) => i !== index);
      setStatusOptions(updated);
      saveSetting('status_options', JSON.stringify(updated), 'general');
    }
  };

  const handleSlaChange = (index: number, value: string) => {
    const updated = [...slaSettings];
    updated[index] = { ...updated[index], value };
    setSlaSettings(updated);
  };

  const saveSlaSettings = () => {
    slaSettings.forEach(s => saveSetting(s.key, s.value, 'sla'));
  };

  const handleTemplateChange = (index: number, value: string) => {
    const updated = [...notifTemplates];
    updated[index] = { ...updated[index], value };
    setNotifTemplates(updated);
  };

  const saveTemplates = () => {
    notifTemplates.forEach(t => saveSetting(t.key, t.value, 'notification_template'));
  };

  if (loading) {
    return <div className="flex items-center justify-center py-20"><Loader2 className="w-8 h-8 animate-spin text-emerald-600" /></div>;
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-foreground">Master Settings</h1>
        <p className="text-sm text-muted-foreground mt-1">Configure complaint types, priorities, statuses, SLA, and notification templates</p>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-2 sm:grid-cols-5 gap-1 h-auto p-1">
          <TabsTrigger value="complaint_types" className="text-xs">Complaint Types</TabsTrigger>
          <TabsTrigger value="priorities" className="text-xs">Priorities</TabsTrigger>
          <TabsTrigger value="statuses" className="text-xs">Statuses</TabsTrigger>
          <TabsTrigger value="sla" className="text-xs">SLA</TabsTrigger>
          <TabsTrigger value="templates" className="text-xs">Templates</TabsTrigger>
        </TabsList>

        {/* Complaint Types */}
        <TabsContent value="complaint_types">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Complaint Types</CardTitle>
              <CardDescription>Manage the types of complaints that can be created</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex flex-wrap gap-2 mb-4">
                {complaintTypes.map((type, idx) => (
                  <div key={idx} className="flex items-center gap-1 bg-emerald-50 dark:bg-emerald-950/30 text-emerald-700 dark:text-emerald-300 rounded-full px-3 py-1.5">
                    <span className="text-sm font-medium">{type}</span>
                    <button onClick={() => handleDeleteItem('complaint_types', idx)} className="text-emerald-400 hover:text-red-500 ml-1"><X className="w-3.5 h-3.5" /></button>
                  </div>
                ))}
              </div>
              <Button size="sm" className="bg-emerald-600 hover:bg-emerald-700" onClick={() => { setAddTarget('complaint_types'); setAddDialogOpen(true); }}>
                <Plus className="w-4 h-4 mr-1" /> Add Type
              </Button>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Priority Levels */}
        <TabsContent value="priorities">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Priority Levels</CardTitle>
              <CardDescription>Configure available priority levels for complaints</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex flex-wrap gap-2 mb-4">
                {priorityLevels.map((level, idx) => (
                  <div key={idx} className="flex items-center gap-1 bg-amber-50 dark:bg-amber-950/30 text-amber-700 dark:text-amber-300 rounded-full px-3 py-1.5">
                    <span className="text-sm font-medium">{level}</span>
                    <button onClick={() => handleDeleteItem('priority_levels', idx)} className="text-amber-400 hover:text-red-500 ml-1"><X className="w-3.5 h-3.5" /></button>
                  </div>
                ))}
              </div>
              <Button size="sm" className="bg-emerald-600 hover:bg-emerald-700" onClick={() => { setAddTarget('priority_levels'); setAddDialogOpen(true); }}>
                <Plus className="w-4 h-4 mr-1" /> Add Priority
              </Button>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Status Options */}
        <TabsContent value="statuses">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Status Options</CardTitle>
              <CardDescription>Define the complaint lifecycle statuses</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex flex-wrap gap-2 mb-4">
                {statusOptions.map((status, idx) => (
                  <div key={idx} className="flex items-center gap-1 bg-blue-50 dark:bg-blue-950/30 text-blue-700 dark:text-blue-300 rounded-full px-3 py-1.5">
                    <span className="text-sm font-medium">{status.replace(/_/g, ' ')}</span>
                    <button onClick={() => handleDeleteItem('status_options', idx)} className="text-blue-400 hover:text-red-500 ml-1"><X className="w-3.5 h-3.5" /></button>
                  </div>
                ))}
              </div>
              <Button size="sm" className="bg-emerald-600 hover:bg-emerald-700" onClick={() => { setAddTarget('status_options'); setAddDialogOpen(true); }}>
                <Plus className="w-4 h-4 mr-1" /> Add Status
              </Button>
            </CardContent>
          </Card>
        </TabsContent>

        {/* SLA Configuration */}
        <TabsContent value="sla">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">SLA Configuration</CardTitle>
              <CardDescription>Set resolution time limits for each priority level</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {slaSettings.map((sla, idx) => (
                  <div key={idx} className="flex items-center gap-4">
                    <Label className="w-48 text-sm font-medium capitalize">{sla.key.replace('sla_', '').replace('_hours', '')}</Label>
                    <Input type="number" value={sla.value} onChange={(e) => handleSlaChange(idx, e.target.value)} className="w-24" />
                    <span className="text-sm text-muted-foreground">hours</span>
                  </div>
                ))}
                <Button size="sm" className="bg-emerald-600 hover:bg-emerald-700" onClick={saveSlaSettings} disabled={saving}>
                  {saving ? <Loader2 className="w-4 h-4 animate-spin mr-1" /> : <Save className="w-4 h-4 mr-1" />}
                  Save SLA Settings
                </Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Notification Templates */}
        <TabsContent value="templates">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Notification Templates</CardTitle>
              <CardDescription>Customize notification messages. Use {'{ticketNumber}'}, {'{engineerName}'}, {'{clientName}'} as placeholders.</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {notifTemplates.map((tmpl, idx) => (
                  <div key={idx} className="space-y-1">
                    <Label className="text-xs font-medium capitalize">{tmpl.key.replace('notif_', '').replace(/_/g, ' ')}</Label>
                    <Textarea value={tmpl.value} onChange={(e) => handleTemplateChange(idx, e.target.value)} rows={2} className="text-sm" />
                  </div>
                ))}
                <Button size="sm" className="bg-emerald-600 hover:bg-emerald-700" onClick={saveTemplates} disabled={saving}>
                  {saving ? <Loader2 className="w-4 h-4 animate-spin mr-1" /> : <Save className="w-4 h-4 mr-1" />}
                  Save Templates
                </Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* Add Item Dialog */}
      <Dialog open={addDialogOpen} onOpenChange={setAddDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Add New {addTarget.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}</DialogTitle>
          </DialogHeader>
          <div className="py-4">
            <Input value={newItemName} onChange={(e) => setNewItemName(e.target.value)} placeholder="Enter name..." onKeyDown={(e) => e.key === 'Enter' && handleAddItem()} />
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setAddDialogOpen(false)}>Cancel</Button>
            <Button className="bg-emerald-600 hover:bg-emerald-700" onClick={handleAddItem}>Add</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
