import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { Save, Loader2, Clock } from 'lucide-react';
import { PriorityTATSettings } from './PriorityTATSettings';
import { EscalationSettings } from './EscalationSettings';
import { WorkingHoursSettings } from './WorkingHoursSettings';
import { getAllConfigurations, updateConfiguration, AdminConfiguration } from '@/services/adminApi';
import { toast } from 'sonner';

interface TATConfigData {
  expressHours: number;
  standardHours: number;
  reminderThreshold1: number;
  reminderThreshold2: number;
  workStartHour: number;
  workEndHour: number;
  workStartDay: number;
  workEndDay: number;
}

export function TATConfig() {
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [config, setConfig] = useState<TATConfigData>({
    expressHours: 24,
    standardHours: 72,
    reminderThreshold1: 50,
    reminderThreshold2: 75,
    workStartHour: 9,
    workEndHour: 18,
    workStartDay: 1,
    workEndDay: 5
  });

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

  const loadConfigurations = async () => {
    try {
      setLoading(true);
      const configs = await getAllConfigurations('TAT_SETTINGS');
      
      // Map configuration values to state
      const configMap: Record<string, string> = {};
      configs.forEach((c: AdminConfiguration) => {
        configMap[c.configKey] = c.configValue;
      });

      setConfig({
        expressHours: parseInt(configMap['DEFAULT_TAT_EXPRESS_HOURS'] || '24'),
        standardHours: parseInt(configMap['DEFAULT_TAT_STANDARD_HOURS'] || '72'),
        reminderThreshold1: parseInt(configMap['TAT_REMINDER_THRESHOLD_1'] || '50'),
        reminderThreshold2: parseInt(configMap['TAT_REMINDER_THRESHOLD_2'] || '75'),
        workStartHour: parseInt(configMap['WORK_START_HOUR'] || '9'),
        workEndHour: parseInt(configMap['WORK_END_HOUR'] || '18'),
        workStartDay: parseInt(configMap['WORK_START_DAY'] || '1'),
        workEndDay: parseInt(configMap['WORK_END_DAY'] || '5')
      });
    } catch (error: any) {
      console.error('Failed to load TAT configurations:', error);
      toast.error('Failed to load TAT configurations');
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    try {
      setSaving(true);
      
      // Save all configurations
      await Promise.all([
        updateConfiguration('DEFAULT_TAT_EXPRESS_HOURS', config.expressHours.toString()),
        updateConfiguration('DEFAULT_TAT_STANDARD_HOURS', config.standardHours.toString()),
        updateConfiguration('TAT_REMINDER_THRESHOLD_1', config.reminderThreshold1.toString()),
        updateConfiguration('TAT_REMINDER_THRESHOLD_2', config.reminderThreshold2.toString()),
        updateConfiguration('WORK_START_HOUR', config.workStartHour.toString()),
        updateConfiguration('WORK_END_HOUR', config.workEndHour.toString()),
        updateConfiguration('WORK_START_DAY', config.workStartDay.toString()),
        updateConfiguration('WORK_END_DAY', config.workEndDay.toString())
      ]);

      toast.success('TAT configuration saved successfully');
      
      // Reload to get updated values
      await loadConfigurations();
    } catch (error: any) {
      console.error('Failed to save TAT configuration:', error);
      toast.error(error.response?.data?.error || 'Failed to save TAT configuration');
    } finally {
      setSaving(false);
    }
  };

  const updateConfig = (updates: Partial<TATConfigData>) => {
    setConfig(prev => ({ ...prev, ...updates }));
  };

  if (loading) {
    return (
      <Card className="shadow-lg border-0 rounded-md">
        <CardContent className="p-12 text-center">
          <Loader2 className="w-8 h-8 animate-spin text-re-green mx-auto mb-4" />
          <p className="text-sm text-gray-600">Loading TAT configuration...</p>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="shadow-lg border-0 rounded-md">
      <CardHeader className="pb-4">
        <div className="flex items-center gap-3">
          <div className="p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md">
            <Clock className="h-5 w-5 text-white" />
          </div>
          <div>
            <CardTitle className="text-lg font-semibold text-gray-900">Turn Around Time (TAT) Configuration</CardTitle>
            <CardDescription className="text-sm text-gray-600">
              Set default TAT hours per priority level, working hours, and configure auto-escalation thresholds
            </CardDescription>
          </div>
        </div>
      </CardHeader>
      <CardContent className="space-y-6">
        <PriorityTATSettings
          expressHours={config.expressHours}
          standardHours={config.standardHours}
          onExpressChange={(hours) => updateConfig({ expressHours: hours })}
          onStandardChange={(hours) => updateConfig({ standardHours: hours })}
        />

        <Separator />

        <WorkingHoursSettings
          workStartHour={config.workStartHour}
          workEndHour={config.workEndHour}
          workStartDay={config.workStartDay}
          workEndDay={config.workEndDay}
          onWorkStartHourChange={(hour) => updateConfig({ workStartHour: hour })}
          onWorkEndHourChange={(hour) => updateConfig({ workEndHour: hour })}
          onWorkStartDayChange={(day) => updateConfig({ workStartDay: day })}
          onWorkEndDayChange={(day) => updateConfig({ workEndDay: day })}
        />

        <Separator />

        <EscalationSettings
          reminderThreshold1={config.reminderThreshold1}
          reminderThreshold2={config.reminderThreshold2}
          onReminderThreshold1Change={(threshold) => updateConfig({ reminderThreshold1: threshold })}
          onReminderThreshold2Change={(threshold) => updateConfig({ reminderThreshold2: threshold })}
        />

        <div className="flex justify-end pt-4">
          <Button 
            onClick={handleSave} 
            disabled={saving}
            className="bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {saving ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Saving...
              </>
            ) : (
              <>
                <Save className="w-4 h-4 mr-2" />
                Save TAT Settings
              </>
            )}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
