import { useState, useEffect } from 'react';
import { apiFetch } from '@/utils/api';
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { toast } from "sonner";
import config from '../../config';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";

interface GlobalSetting {
  setting_key: string;
  setting_value: string;
  description: string;
  updated_at: string;
}

export function GlobalSettings() {
  const [settings, setSettings] = useState<GlobalSetting[]>([]);
  const [loading, setLoading] = useState(true);

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

  const loadSettings = async () => {
    try {
      setLoading(true);
      const response = await apiFetch(`${config.apiUrl}/config/global`, {
        credentials: 'include'
      });
      if (!response.ok) {
        throw new Error('Failed to load global settings');
      }
      const data = await response.json();
      setSettings(data);
    } catch (error) {
      toast.error(`Failed to load settings: ${error instanceof Error ? error.message : 'Unknown error'}`);
    } finally {
      setLoading(false);
    }
  };

  const updateSetting = async (key: string, value: string) => {
    const updatedSettings = settings.map(s => 
      s.setting_key === key ? { ...s, setting_value: value } : s
    );
    setSettings(updatedSettings);
  };

  const handleSaveSettings = async () => {
    try {
      const response = await apiFetch(`${config.apiUrl}/config/global`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        credentials: 'include',
        body: JSON.stringify(settings)
      });

      if (!response.ok) {
        const data = await response.json().catch(() => ({}));
        throw new Error(data.error || 'Failed to update global settings');
      }

      toast.success('Global settings updated successfully');
      await loadSettings(); // Reload to get fresh data
    } catch (error) {
      toast.error(`Failed to update settings: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  };

  const renderSettingInput = (setting: GlobalSetting) => {
    // Handle different input types based on setting key or value
    if (setting.setting_key === 'abc_calculation_basis') {
      return (
        <Select 
          value={setting.setting_value}
          onValueChange={(value) => updateSetting(setting.setting_key, value)}
        >
          <SelectTrigger>
            <SelectValue placeholder="Select calculation basis" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="revenue_30d">Revenue (30 days)</SelectItem>
            <SelectItem value="sales_30d">Sales Quantity (30 days)</SelectItem>
            <SelectItem value="lifetime_revenue">Lifetime Revenue</SelectItem>
          </SelectContent>
        </Select>
      );
    } else if (setting.setting_key === 'default_forecast_method') {
      return (
        <Select
          value={setting.setting_value}
          onValueChange={(value) => updateSetting(setting.setting_key, value)}
        >
          <SelectTrigger>
            <SelectValue placeholder="Select forecast method" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="standard">Standard</SelectItem>
            <SelectItem value="seasonal">Seasonal</SelectItem>
          </SelectContent>
        </Select>
      );
    } else if (setting.setting_key.includes('threshold')) {
      // Percentage inputs
      return (
        <Input
          type="number"
          min="0"
          max="1"
          step="0.01"
          className="[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
          value={setting.setting_value}
          onChange={(e) => updateSetting(setting.setting_key, e.target.value)}
        />
      );
    } else {
      // Default to number input for other settings
      return (
        <Input
          type="number"
          min="0"
          className="[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
          value={setting.setting_value}
          onChange={(e) => updateSetting(setting.setting_key, e.target.value)}
        />
      );
    }
  };

  // Group settings by their purpose
  const abcSettings = settings.filter(s => s.setting_key.startsWith('abc_'));
  const defaultSettings = settings.filter(s => s.setting_key.startsWith('default_'));
  
  if (loading) {
    return <div className="py-4">Loading settings...</div>;
  }

  return (
    <div className="max-w-[700px] space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>ABC Classification Settings</CardTitle>
          <CardDescription>Configure how products are classified into A, B, and C categories</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {abcSettings.map(setting => (
              <div key={setting.setting_key} className="grid gap-2">
                <Label htmlFor={setting.setting_key}>
                  {setting.description}
                </Label>
                {renderSettingInput(setting)}
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Default Settings</CardTitle>
          <CardDescription>Configure system-wide default values</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {defaultSettings.map(setting => (
              <div key={setting.setting_key} className="grid gap-2">
                <Label htmlFor={setting.setting_key}>
                  {setting.description}
                </Label>
                {renderSettingInput(setting)}
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      <div className="flex justify-end">
        <Button onClick={handleSaveSettings}>
          Save All Settings
        </Button>
      </div>
    </div>
  );
} 
