"use client";

import { useState, useEffect } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { ProtectedLayout } from "@/components/protected-layout";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } 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 { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/hooks/use-toast";
import {
  Settings,
  Phone,
  MessageSquare,
  Mail,
  Save,
  RefreshCw,
  Shield,
  Clock,
  Globe,
  Key,
  AlertTriangle,
} from "lucide-react";

interface SettingsData {
  CALLS?: Record<string, { value: string; description: string | null }>;
  SMS?: Record<string, { value: string; description: string | null }>;
  EMAIL?: Record<string, { value: string; description: string | null }>;
}

const defaultSettings = {
  CALLS: {
    enabled: { value: "true", description: "Enable call functionality" },
    primaryCarrier: { value: "safaricom", description: "Primary carrier for outbound calls" },
    workingHoursStart: { value: "08:00", description: "Start of working hours" },
    workingHoursEnd: { value: "18:00", description: "End of working hours" },
    maxCallsPerDay: { value: "50", description: "Maximum calls per agent per day" },
    callRecording: { value: "false", description: "Enable call recording" },
    autoDialerEnabled: { value: "false", description: "Enable auto-dialer feature" },
    // Safaricom Kenya Configuration
    safaricomEnabled: { value: "true", description: "Enable Safaricom calls" },
    safaricomApiKey: { value: "", description: "Safaricom API Key" },
    safaricomApiSecret: { value: "", description: "Safaricom API Secret" },
    safaricomShortcode: { value: "", description: "Safaricom Business Shortcode" },
    safaricomCallbackUrl: { value: "", description: "Safaricom Callback URL" },
    safaricomEnvironment: { value: "sandbox", description: "Safaricom Environment (sandbox/production)" },
    // Airtel Kenya Configuration
    airtelEnabled: { value: "false", description: "Enable Airtel calls" },
    airtelApiKey: { value: "", description: "Airtel API Key" },
    airtelApiSecret: { value: "", description: "Airtel API Secret" },
    airtelServiceId: { value: "", description: "Airtel Service ID" },
    airtelCallbackUrl: { value: "", description: "Airtel Callback URL" },
    airtelEnvironment: { value: "sandbox", description: "Airtel Environment (sandbox/production)" },
  },
  SMS: {
    enabled: { value: "true", description: "Enable SMS functionality" },
    primaryProvider: { value: "africas_talking", description: "Primary SMS provider" },
    maxSmsPerDay: { value: "500", description: "Maximum SMS per day" },
    // Africa's Talking Configuration (supports both Safaricom & Airtel)
    atEnabled: { value: "true", description: "Enable Africa's Talking" },
    atApiKey: { value: "", description: "Africa's Talking API Key" },
    atUsername: { value: "sandbox", description: "Africa's Talking Username" },
    atSenderId: { value: "GRECO", description: "Africa's Talking Sender ID" },
    atEnvironment: { value: "sandbox", description: "Africa's Talking Environment" },
    // Safaricom SMS (Daraja API)
    safaricomSmsEnabled: { value: "false", description: "Enable Safaricom Daraja SMS" },
    safaricomSmsApiKey: { value: "", description: "Safaricom SMS Consumer Key" },
    safaricomSmsApiSecret: { value: "", description: "Safaricom SMS Consumer Secret" },
    safaricomSmsShortcode: { value: "", description: "Safaricom SMS Shortcode" },
    safaricomSmsSenderId: { value: "", description: "Safaricom SMS Sender ID" },
    safaricomSmsCallbackUrl: { value: "", description: "Safaricom SMS Callback URL" },
    safaricomSmsEnvironment: { value: "sandbox", description: "Safaricom SMS Environment" },
    // Airtel SMS
    airtelSmsEnabled: { value: "false", description: "Enable Airtel SMS" },
    airtelSmsApiKey: { value: "", description: "Airtel SMS API Key" },
    airtelSmsApiSecret: { value: "", description: "Airtel SMS API Secret" },
    airtelSmsServiceId: { value: "", description: "Airtel SMS Service ID" },
    airtelSmsSenderId: { value: "", description: "Airtel SMS Sender ID" },
    airtelSmsCallbackUrl: { value: "", description: "Airtel SMS Callback URL" },
    airtelSmsEnvironment: { value: "sandbox", description: "Airtel SMS Environment" },
    // Templates
    templateReminder: { value: "Dear {{customerName}}, this is a reminder about your payment of KES {{amount}}. Please pay by {{promisedDate}}.", description: "Default reminder template" },
    templateOverdue: { value: "Dear {{customerName}}, your payment of KES {{amount}} is overdue. Please make payment immediately to avoid further action.", description: "Default overdue template" },
  },
  EMAIL: {
    enabled: { value: "false", description: "Enable email functionality" },
    smtpHost: { value: "", description: "SMTP server host" },
    smtpPort: { value: "587", description: "SMTP server port" },
    smtpUser: { value: "", description: "SMTP username" },
    smtpPassword: { value: "", description: "SMTP password" },
    fromEmail: { value: "", description: "From email address" },
    fromName: { value: "GRECO Collections", description: "From name" },
    templateReminder: { value: "", description: "Default reminder email template" },
  },
};

export default function SettingsPage() {
  const { data: session, status } = useSession();
  const router = useRouter();
  const { toast } = useToast();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState<string | null>(null);
  const [settings, setSettings] = useState<SettingsData>(defaultSettings);

  // Redirect non-admins
  useEffect(() => {
    if (status === "authenticated" && session?.user?.role !== "ADMIN") {
      router.push("/dashboard");
      toast({
        title: "Access Denied",
        description: "Only administrators can access settings.",
        variant: "destructive",
      });
    }
  }, [status, session, router, toast]);

  // Fetch settings
  useEffect(() => {
    const fetchSettings = async () => {
      try {
        const res = await fetch("/api/settings");
        if (res.ok) {
          const data = await res.json();
          // Merge with defaults
          const merged = { ...defaultSettings };
          Object.keys(data.settings || {}).forEach((category) => {
            if (merged[category as keyof typeof merged]) {
              merged[category as keyof typeof merged] = {
                ...merged[category as keyof typeof merged],
                ...data.settings[category],
              };
            }
          });
          setSettings(merged);
        }
      } catch (error) {
        console.error("Failed to fetch settings:", error);
      } finally {
        setLoading(false);
      }
    };

    if (status === "authenticated" && session?.user?.role === "ADMIN") {
      fetchSettings();
    }
  }, [status, session]);

  const updateSetting = (category: string, key: string, value: string) => {
    setSettings((prev) => ({
      ...prev,
      [category]: {
        ...prev[category as keyof typeof prev],
        [key]: {
          ...prev[category as keyof typeof prev]?.[key],
          value,
        },
      },
    }));
  };

  const saveSettings = async (category: string) => {
    setSaving(category);
    try {
      const categorySettings = settings[category as keyof typeof settings];
      const payload = Object.entries(categorySettings || {}).reduce(
        (acc, [key, data]) => {
          acc[key] = { value: data.value, description: data.description };
          return acc;
        },
        {} as Record<string, { value: string; description: string | null }>
      );

      const res = await fetch("/api/settings", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ category, settings: payload }),
      });

      if (res.ok) {
        toast({
          title: "Settings Saved",
          description: `${category} settings have been updated successfully.`,
        });
      } else {
        throw new Error("Failed to save");
      }
    } catch (error) {
      console.error("Error saving settings:", error);
      toast({
        title: "Error",
        description: "Failed to save settings. Please try again.",
        variant: "destructive",
      });
    } finally {
      setSaving(null);
    }
  };

  if (status === "loading" || loading) {
    return (
      <ProtectedLayout>
        <div className="flex items-center justify-center min-h-[400px]">
          <RefreshCw className="h-8 w-8 animate-spin text-muted-foreground" />
        </div>
      </ProtectedLayout>
    );
  }

  if (session?.user?.role !== "ADMIN") {
    return null;
  }

  return (
    <ProtectedLayout>
      <div className="space-y-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold flex items-center gap-2">
              <Settings className="h-8 w-8" />
              System Settings
            </h1>
            <p className="text-muted-foreground mt-1">
              Configure communication channels and system preferences
            </p>
          </div>
        </div>

        {/* Warning Banner */}
        <Card className="border-yellow-500 bg-yellow-50">
          <CardContent className="py-4">
            <div className="flex items-start gap-3">
              <AlertTriangle className="h-5 w-5 text-yellow-600 mt-0.5" />
              <div>
                <p className="font-medium text-yellow-800">Administrator Access Only</p>
                <p className="text-sm text-yellow-700">
                  Changes to these settings will affect all users and communication channels.
                  Please ensure you have the correct credentials before saving.
                </p>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Settings Tabs */}
        <Tabs defaultValue="calls" className="space-y-4">
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="calls" className="flex items-center gap-2">
              <Phone className="h-4 w-4" />
              Calls
            </TabsTrigger>
            <TabsTrigger value="sms" className="flex items-center gap-2">
              <MessageSquare className="h-4 w-4" />
              SMS
            </TabsTrigger>
            <TabsTrigger value="email" className="flex items-center gap-2">
              <Mail className="h-4 w-4" />
              Email
            </TabsTrigger>
          </TabsList>

          {/* Calls Settings */}
          <TabsContent value="calls" className="space-y-4">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Phone className="h-5 w-5" />
                  Call Configuration
                </CardTitle>
                <CardDescription>
                  Configure call settings and carrier integrations for Safaricom and Airtel Kenya
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Enable/Disable */}
                <div className="flex items-center justify-between p-4 border rounded-lg">
                  <div className="space-y-0.5">
                    <Label className="text-base">Enable Calls</Label>
                    <p className="text-sm text-muted-foreground">
                      Turn on/off call functionality for the system
                    </p>
                  </div>
                  <Switch
                    checked={settings.CALLS?.enabled?.value === "true"}
                    onCheckedChange={(checked) =>
                      updateSetting("CALLS", "enabled", String(checked))
                    }
                  />
                </div>

                {/* Primary Carrier Selection */}
                <div className="space-y-2">
                  <Label>Primary Carrier</Label>
                  <select
                    className="w-full p-2 border rounded-md"
                    value={settings.CALLS?.primaryCarrier?.value || "safaricom"}
                    onChange={(e) => updateSetting("CALLS", "primaryCarrier", e.target.value)}
                  >
                    <option value="safaricom">Safaricom Kenya</option>
                    <option value="airtel">Airtel Kenya</option>
                  </select>
                  <p className="text-sm text-muted-foreground">
                    Select the default carrier for outbound calls
                  </p>
                </div>

                {/* Working Hours */}
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label className="flex items-center gap-2">
                      <Clock className="h-4 w-4" />
                      Working Hours Start
                    </Label>
                    <Input
                      type="time"
                      value={settings.CALLS?.workingHoursStart?.value || "08:00"}
                      onChange={(e) =>
                        updateSetting("CALLS", "workingHoursStart", e.target.value)
                      }
                    />
                  </div>
                  <div className="space-y-2">
                    <Label className="flex items-center gap-2">
                      <Clock className="h-4 w-4" />
                      Working Hours End
                    </Label>
                    <Input
                      type="time"
                      value={settings.CALLS?.workingHoursEnd?.value || "18:00"}
                      onChange={(e) =>
                        updateSetting("CALLS", "workingHoursEnd", e.target.value)
                      }
                    />
                  </div>
                </div>

                {/* Max Calls */}
                <div className="space-y-2">
                  <Label>Maximum Calls Per Agent Per Day</Label>
                  <Input
                    type="number"
                    min="1"
                    max="200"
                    value={settings.CALLS?.maxCallsPerDay?.value || "50"}
                    onChange={(e) =>
                      updateSetting("CALLS", "maxCallsPerDay", e.target.value)
                    }
                  />
                </div>

                {/* Call Recording & Auto Dialer */}
                <div className="grid grid-cols-2 gap-4">
                  <div className="flex items-center justify-between p-4 border rounded-lg">
                    <div className="space-y-0.5">
                      <Label className="text-base">Call Recording</Label>
                      <p className="text-xs text-muted-foreground">
                        Record calls for QA
                      </p>
                    </div>
                    <Switch
                      checked={settings.CALLS?.callRecording?.value === "true"}
                      onCheckedChange={(checked) =>
                        updateSetting("CALLS", "callRecording", String(checked))
                      }
                    />
                  </div>
                  <div className="flex items-center justify-between p-4 border rounded-lg">
                    <div className="space-y-0.5">
                      <Label className="text-base">Auto-Dialer</Label>
                      <p className="text-xs text-muted-foreground">
                        Auto-dial feature
                      </p>
                    </div>
                    <Switch
                      checked={settings.CALLS?.autoDialerEnabled?.value === "true"}
                      onCheckedChange={(checked) =>
                        updateSetting("CALLS", "autoDialerEnabled", String(checked))
                      }
                    />
                  </div>
                </div>

                {/* Safaricom Kenya Configuration */}
                <div className="space-y-4 p-4 border rounded-lg bg-green-50">
                  <div className="flex items-center justify-between">
                    <h4 className="font-medium flex items-center gap-2 text-green-800">
                      <Shield className="h-4 w-4" />
                      Safaricom Kenya - Voice API
                    </h4>
                    <Switch
                      checked={settings.CALLS?.safaricomEnabled?.value === "true"}
                      onCheckedChange={(checked) =>
                        updateSetting("CALLS", "safaricomEnabled", String(checked))
                      }
                    />
                  </div>
                  <p className="text-xs text-green-700">
                    Configure Safaricom Business API credentials from{" "}
                    <a href="https://developer.safaricom.co.ke/" target="_blank" rel="noopener noreferrer" className="underline">
                      Safaricom Daraja Portal
                    </a>
                  </p>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>Consumer Key</Label>
                      <Input
                        type="password"
                        value={settings.CALLS?.safaricomApiKey?.value || ""}
                        onChange={(e) =>
                          updateSetting("CALLS", "safaricomApiKey", e.target.value)
                        }
                        placeholder="Enter Consumer Key"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>Consumer Secret</Label>
                      <Input
                        type="password"
                        value={settings.CALLS?.safaricomApiSecret?.value || ""}
                        onChange={(e) =>
                          updateSetting("CALLS", "safaricomApiSecret", e.target.value)
                        }
                        placeholder="Enter Consumer Secret"
                      />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>Business Shortcode</Label>
                      <Input
                        value={settings.CALLS?.safaricomShortcode?.value || ""}
                        onChange={(e) =>
                          updateSetting("CALLS", "safaricomShortcode", e.target.value)
                        }
                        placeholder="e.g., 174379"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>Environment</Label>
                      <select
                        className="w-full p-2 border rounded-md"
                        value={settings.CALLS?.safaricomEnvironment?.value || "sandbox"}
                        onChange={(e) => updateSetting("CALLS", "safaricomEnvironment", e.target.value)}
                      >
                        <option value="sandbox">Sandbox (Testing)</option>
                        <option value="production">Production (Live)</option>
                      </select>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label>Callback URL</Label>
                    <Input
                      value={settings.CALLS?.safaricomCallbackUrl?.value || ""}
                      onChange={(e) =>
                        updateSetting("CALLS", "safaricomCallbackUrl", e.target.value)
                      }
                      placeholder="https://yourdomain.com/api/safaricom/callback"
                    />
                  </div>
                </div>

                {/* Airtel Kenya Configuration */}
                <div className="space-y-4 p-4 border rounded-lg bg-red-50">
                  <div className="flex items-center justify-between">
                    <h4 className="font-medium flex items-center gap-2 text-red-800">
                      <Shield className="h-4 w-4" />
                      Airtel Kenya - Voice API
                    </h4>
                    <Switch
                      checked={settings.CALLS?.airtelEnabled?.value === "true"}
                      onCheckedChange={(checked) =>
                        updateSetting("CALLS", "airtelEnabled", String(checked))
                      }
                    />
                  </div>
                  <p className="text-xs text-red-700">
                    Configure Airtel Business API credentials from{" "}
                    <a href="https://developers.airtel.africa/" target="_blank" rel="noopener noreferrer" className="underline">
                      Airtel Developer Portal
                    </a>
                  </p>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>API Key</Label>
                      <Input
                        type="password"
                        value={settings.CALLS?.airtelApiKey?.value || ""}
                        onChange={(e) =>
                          updateSetting("CALLS", "airtelApiKey", e.target.value)
                        }
                        placeholder="Enter API Key"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>API Secret</Label>
                      <Input
                        type="password"
                        value={settings.CALLS?.airtelApiSecret?.value || ""}
                        onChange={(e) =>
                          updateSetting("CALLS", "airtelApiSecret", e.target.value)
                        }
                        placeholder="Enter API Secret"
                      />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>Service ID</Label>
                      <Input
                        value={settings.CALLS?.airtelServiceId?.value || ""}
                        onChange={(e) =>
                          updateSetting("CALLS", "airtelServiceId", e.target.value)
                        }
                        placeholder="Enter Service ID"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>Environment</Label>
                      <select
                        className="w-full p-2 border rounded-md"
                        value={settings.CALLS?.airtelEnvironment?.value || "sandbox"}
                        onChange={(e) => updateSetting("CALLS", "airtelEnvironment", e.target.value)}
                      >
                        <option value="sandbox">Sandbox (Testing)</option>
                        <option value="production">Production (Live)</option>
                      </select>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label>Callback URL</Label>
                    <Input
                      value={settings.CALLS?.airtelCallbackUrl?.value || ""}
                      onChange={(e) =>
                        updateSetting("CALLS", "airtelCallbackUrl", e.target.value)
                      }
                      placeholder="https://yourdomain.com/api/airtel/callback"
                    />
                  </div>
                </div>

                <Button
                  onClick={() => saveSettings("CALLS")}
                  disabled={saving === "CALLS"}
                  className="w-full"
                >
                  {saving === "CALLS" ? (
                    <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                  ) : (
                    <Save className="h-4 w-4 mr-2" />
                  )}
                  Save Call Settings
                </Button>
              </CardContent>
            </Card>
          </TabsContent>

          {/* SMS Settings */}
          <TabsContent value="sms" className="space-y-4">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <MessageSquare className="h-5 w-5" />
                  SMS Configuration
                </CardTitle>
                <CardDescription>
                  Configure SMS gateway credentials for Africa&apos;s Talking, Safaricom Daraja, and Airtel Kenya
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Enable/Disable */}
                <div className="flex items-center justify-between p-4 border rounded-lg">
                  <div className="space-y-0.5">
                    <Label className="text-base">Enable SMS</Label>
                    <p className="text-sm text-muted-foreground">
                      Turn on/off SMS functionality for the system
                    </p>
                  </div>
                  <Switch
                    checked={settings.SMS?.enabled?.value === "true"}
                    onCheckedChange={(checked) =>
                      updateSetting("SMS", "enabled", String(checked))
                    }
                  />
                </div>

                {/* Primary Provider Selection */}
                <div className="space-y-2">
                  <Label>Primary SMS Provider</Label>
                  <select
                    className="w-full p-2 border rounded-md"
                    value={settings.SMS?.primaryProvider?.value || "africas_talking"}
                    onChange={(e) => updateSetting("SMS", "primaryProvider", e.target.value)}
                  >
                    <option value="africas_talking">Africa&apos;s Talking (Recommended)</option>
                    <option value="safaricom">Safaricom Daraja SMS</option>
                    <option value="airtel">Airtel Kenya SMS</option>
                  </select>
                  <p className="text-sm text-muted-foreground">
                    Africa&apos;s Talking supports both Safaricom and Airtel numbers
                  </p>
                </div>

                {/* Max SMS */}
                <div className="space-y-2">
                  <Label>Maximum SMS Per Day</Label>
                  <Input
                    type="number"
                    min="1"
                    max="10000"
                    value={settings.SMS?.maxSmsPerDay?.value || "500"}
                    onChange={(e) =>
                      updateSetting("SMS", "maxSmsPerDay", e.target.value)
                    }
                  />
                </div>

                {/* Africa's Talking Configuration */}
                <div className="space-y-4 p-4 border rounded-lg bg-blue-50">
                  <div className="flex items-center justify-between">
                    <h4 className="font-medium flex items-center gap-2 text-blue-800">
                      <Key className="h-4 w-4" />
                      Africa&apos;s Talking SMS API
                    </h4>
                    <Switch
                      checked={settings.SMS?.atEnabled?.value === "true"}
                      onCheckedChange={(checked) =>
                        updateSetting("SMS", "atEnabled", String(checked))
                      }
                    />
                  </div>
                  <p className="text-xs text-blue-700">
                    Recommended provider - supports both Safaricom and Airtel numbers.{" "}
                    <a href="https://africastalking.com/" target="_blank" rel="noopener noreferrer" className="underline">
                      Get credentials
                    </a>
                  </p>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>Username</Label>
                      <Input
                        value={settings.SMS?.atUsername?.value || ""}
                        onChange={(e) =>
                          updateSetting("SMS", "atUsername", e.target.value)
                        }
                        placeholder="sandbox"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>API Key</Label>
                      <Input
                        type="password"
                        value={settings.SMS?.atApiKey?.value || ""}
                        onChange={(e) =>
                          updateSetting("SMS", "atApiKey", e.target.value)
                        }
                        placeholder="Enter API Key"
                      />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>Sender ID</Label>
                      <Input
                        value={settings.SMS?.atSenderId?.value || ""}
                        onChange={(e) =>
                          updateSetting("SMS", "atSenderId", e.target.value)
                        }
                        placeholder="GRECO"
                      />
                      <p className="text-xs text-muted-foreground">Max 11 characters</p>
                    </div>
                    <div className="space-y-2">
                      <Label>Environment</Label>
                      <select
                        className="w-full p-2 border rounded-md"
                        value={settings.SMS?.atEnvironment?.value || "sandbox"}
                        onChange={(e) => updateSetting("SMS", "atEnvironment", e.target.value)}
                      >
                        <option value="sandbox">Sandbox (Testing)</option>
                        <option value="production">Production (Live)</option>
                      </select>
                    </div>
                  </div>
                </div>

                {/* Safaricom Daraja SMS Configuration */}
                <div className="space-y-4 p-4 border rounded-lg bg-green-50">
                  <div className="flex items-center justify-between">
                    <h4 className="font-medium flex items-center gap-2 text-green-800">
                      <Shield className="h-4 w-4" />
                      Safaricom Daraja SMS API
                    </h4>
                    <Switch
                      checked={settings.SMS?.safaricomSmsEnabled?.value === "true"}
                      onCheckedChange={(checked) =>
                        updateSetting("SMS", "safaricomSmsEnabled", String(checked))
                      }
                    />
                  </div>
                  <p className="text-xs text-green-700">
                    Direct Safaricom SMS integration.{" "}
                    <a href="https://developer.safaricom.co.ke/" target="_blank" rel="noopener noreferrer" className="underline">
                      Safaricom Daraja Portal
                    </a>
                  </p>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>Consumer Key</Label>
                      <Input
                        type="password"
                        value={settings.SMS?.safaricomSmsApiKey?.value || ""}
                        onChange={(e) =>
                          updateSetting("SMS", "safaricomSmsApiKey", e.target.value)
                        }
                        placeholder="Enter Consumer Key"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>Consumer Secret</Label>
                      <Input
                        type="password"
                        value={settings.SMS?.safaricomSmsApiSecret?.value || ""}
                        onChange={(e) =>
                          updateSetting("SMS", "safaricomSmsApiSecret", e.target.value)
                        }
                        placeholder="Enter Consumer Secret"
                      />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>Shortcode</Label>
                      <Input
                        value={settings.SMS?.safaricomSmsShortcode?.value || ""}
                        onChange={(e) =>
                          updateSetting("SMS", "safaricomSmsShortcode", e.target.value)
                        }
                        placeholder="e.g., 123456"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>Sender ID</Label>
                      <Input
                        value={settings.SMS?.safaricomSmsSenderId?.value || ""}
                        onChange={(e) =>
                          updateSetting("SMS", "safaricomSmsSenderId", e.target.value)
                        }
                        placeholder="GRECO"
                      />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>Callback URL</Label>
                      <Input
                        value={settings.SMS?.safaricomSmsCallbackUrl?.value || ""}
                        onChange={(e) =>
                          updateSetting("SMS", "safaricomSmsCallbackUrl", e.target.value)
                        }
                        placeholder="https://yourdomain.com/api/sms/safaricom/callback"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>Environment</Label>
                      <select
                        className="w-full p-2 border rounded-md"
                        value={settings.SMS?.safaricomSmsEnvironment?.value || "sandbox"}
                        onChange={(e) => updateSetting("SMS", "safaricomSmsEnvironment", e.target.value)}
                      >
                        <option value="sandbox">Sandbox (Testing)</option>
                        <option value="production">Production (Live)</option>
                      </select>
                    </div>
                  </div>
                </div>

                {/* Airtel Kenya SMS Configuration */}
                <div className="space-y-4 p-4 border rounded-lg bg-red-50">
                  <div className="flex items-center justify-between">
                    <h4 className="font-medium flex items-center gap-2 text-red-800">
                      <Shield className="h-4 w-4" />
                      Airtel Kenya SMS API
                    </h4>
                    <Switch
                      checked={settings.SMS?.airtelSmsEnabled?.value === "true"}
                      onCheckedChange={(checked) =>
                        updateSetting("SMS", "airtelSmsEnabled", String(checked))
                      }
                    />
                  </div>
                  <p className="text-xs text-red-700">
                    Direct Airtel SMS integration.{" "}
                    <a href="https://developers.airtel.africa/" target="_blank" rel="noopener noreferrer" className="underline">
                      Airtel Developer Portal
                    </a>
                  </p>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>API Key</Label>
                      <Input
                        type="password"
                        value={settings.SMS?.airtelSmsApiKey?.value || ""}
                        onChange={(e) =>
                          updateSetting("SMS", "airtelSmsApiKey", e.target.value)
                        }
                        placeholder="Enter API Key"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>API Secret</Label>
                      <Input
                        type="password"
                        value={settings.SMS?.airtelSmsApiSecret?.value || ""}
                        onChange={(e) =>
                          updateSetting("SMS", "airtelSmsApiSecret", e.target.value)
                        }
                        placeholder="Enter API Secret"
                      />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>Service ID</Label>
                      <Input
                        value={settings.SMS?.airtelSmsServiceId?.value || ""}
                        onChange={(e) =>
                          updateSetting("SMS", "airtelSmsServiceId", e.target.value)
                        }
                        placeholder="Enter Service ID"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>Sender ID</Label>
                      <Input
                        value={settings.SMS?.airtelSmsSenderId?.value || ""}
                        onChange={(e) =>
                          updateSetting("SMS", "airtelSmsSenderId", e.target.value)
                        }
                        placeholder="GRECO"
                      />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>Callback URL</Label>
                      <Input
                        value={settings.SMS?.airtelSmsCallbackUrl?.value || ""}
                        onChange={(e) =>
                          updateSetting("SMS", "airtelSmsCallbackUrl", e.target.value)
                        }
                        placeholder="https://yourdomain.com/api/sms/airtel/callback"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>Environment</Label>
                      <select
                        className="w-full p-2 border rounded-md"
                        value={settings.SMS?.airtelSmsEnvironment?.value || "sandbox"}
                        onChange={(e) => updateSetting("SMS", "airtelSmsEnvironment", e.target.value)}
                      >
                        <option value="sandbox">Sandbox (Testing)</option>
                        <option value="production">Production (Live)</option>
                      </select>
                    </div>
                  </div>
                </div>

                {/* Templates */}
                <div className="space-y-4 p-4 border rounded-lg">
                  <h4 className="font-medium">Message Templates</h4>
                  <div className="space-y-2">
                    <Label>Reminder Template</Label>
                    <Textarea
                      rows={3}
                      value={settings.SMS?.templateReminder?.value || ""}
                      onChange={(e) =>
                        updateSetting("SMS", "templateReminder", e.target.value)
                      }
                      placeholder="Dear {{customerName}}, ..."
                    />
                    <p className="text-xs text-muted-foreground">
                      Variables: {"{{customerName}}, {{amount}}, {{promisedDate}}, {{promisedAmount}}"}
                    </p>
                  </div>
                  <div className="space-y-2">
                    <Label>Overdue Template</Label>
                    <Textarea
                      rows={3}
                      value={settings.SMS?.templateOverdue?.value || ""}
                      onChange={(e) =>
                        updateSetting("SMS", "templateOverdue", e.target.value)
                      }
                      placeholder="Dear {{customerName}}, your payment is overdue..."
                    />
                  </div>
                </div>

                <Button
                  onClick={() => saveSettings("SMS")}
                  disabled={saving === "SMS"}
                  className="w-full"
                >
                  {saving === "SMS" ? (
                    <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                  ) : (
                    <Save className="h-4 w-4 mr-2" />
                  )}
                  Save SMS Settings
                </Button>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Email Settings */}
          <TabsContent value="email" className="space-y-4">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Mail className="h-5 w-5" />
                  Email Configuration
                </CardTitle>
                <CardDescription>
                  Configure SMTP settings for email notifications
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Enable/Disable */}
                <div className="flex items-center justify-between p-4 border rounded-lg">
                  <div className="space-y-0.5">
                    <Label className="text-base">Enable Email</Label>
                    <p className="text-sm text-muted-foreground">
                      Turn on/off email functionality for the system
                    </p>
                  </div>
                  <Switch
                    checked={settings.EMAIL?.enabled?.value === "true"}
                    onCheckedChange={(checked) =>
                      updateSetting("EMAIL", "enabled", String(checked))
                    }
                  />
                </div>

                {/* SMTP Settings */}
                <div className="space-y-4 p-4 border rounded-lg">
                  <h4 className="font-medium flex items-center gap-2">
                    <Globe className="h-4 w-4" />
                    SMTP Server Settings
                  </h4>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>SMTP Host</Label>
                      <Input
                        value={settings.EMAIL?.smtpHost?.value || ""}
                        onChange={(e) =>
                          updateSetting("EMAIL", "smtpHost", e.target.value)
                        }
                        placeholder="smtp.gmail.com"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>SMTP Port</Label>
                      <Input
                        type="number"
                        value={settings.EMAIL?.smtpPort?.value || "587"}
                        onChange={(e) =>
                          updateSetting("EMAIL", "smtpPort", e.target.value)
                        }
                        placeholder="587"
                      />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>SMTP Username</Label>
                      <Input
                        value={settings.EMAIL?.smtpUser?.value || ""}
                        onChange={(e) =>
                          updateSetting("EMAIL", "smtpUser", e.target.value)
                        }
                        placeholder="your-email@gmail.com"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>SMTP Password</Label>
                      <Input
                        type="password"
                        value={settings.EMAIL?.smtpPassword?.value || ""}
                        onChange={(e) =>
                          updateSetting("EMAIL", "smtpPassword", e.target.value)
                        }
                        placeholder="Enter password"
                      />
                    </div>
                  </div>
                </div>

                {/* From Settings */}
                <div className="space-y-4 p-4 border rounded-lg">
                  <h4 className="font-medium">Sender Information</h4>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>From Email</Label>
                      <Input
                        type="email"
                        value={settings.EMAIL?.fromEmail?.value || ""}
                        onChange={(e) =>
                          updateSetting("EMAIL", "fromEmail", e.target.value)
                        }
                        placeholder="collections@company.com"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>From Name</Label>
                      <Input
                        value={settings.EMAIL?.fromName?.value || ""}
                        onChange={(e) =>
                          updateSetting("EMAIL", "fromName", e.target.value)
                        }
                        placeholder="GRECO Collections"
                      />
                    </div>
                  </div>
                </div>

                {/* Email Template */}
                <div className="space-y-2">
                  <Label>Default Reminder Email Template</Label>
                  <Textarea
                    rows={6}
                    value={settings.EMAIL?.templateReminder?.value || ""}
                    onChange={(e) =>
                      updateSetting("EMAIL", "templateReminder", e.target.value)
                    }
                    placeholder="Dear {{customerName}},\n\nThis is a reminder about your outstanding balance..."
                  />
                  <p className="text-xs text-muted-foreground">
                    Variables: {"{{customerName}}, {{amount}}, {{promisedDate}}, {{promisedAmount}}"}
                  </p>
                </div>

                <Button
                  onClick={() => saveSettings("EMAIL")}
                  disabled={saving === "EMAIL"}
                  className="w-full"
                >
                  {saving === "EMAIL" ? (
                    <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                  ) : (
                    <Save className="h-4 w-4 mr-2" />
                  )}
                  Save Email Settings
                </Button>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
    </ProtectedLayout>
  );
}
