'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from '@/lib/i18n';
import {
  Radio, Mail, MessageSquare, Bell, Send, Loader2, Save, TestTube, CheckCircle2, Settings,
} 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 { Textarea } from '@/components/ui/textarea';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { useToast } from '@/hooks/use-toast';
import { authFetch } from '@/lib/api';

interface ChannelConfig {
  enabled: boolean;
  [key: string]: unknown;
}

interface ChannelState {
  whatsapp: ChannelConfig;
  email: ChannelConfig;
  sms: ChannelConfig;
  inApp: ChannelConfig;
  push: ChannelConfig;
}

const defaultConfig: ChannelState = {
  whatsapp: {
    enabled: false,
    apiKey: '',
    phoneNumber: '',
    templateMessages: 'New complaint {{ticketNumber}} assigned to you. Priority: {{priority}}',
  },
  email: {
    enabled: false,
    smtpHost: '',
    smtpPort: '587',
    smtpUsername: '',
    smtpPassword: '',
    emailTemplates: 'Subject: New Complaint {{ticketNumber}}\n\nDear {{name}},\n\nA new complaint has been assigned to you.\n\nTicket: {{ticketNumber}}\nPriority: {{priority}}\nDescription: {{description}}',
  },
  sms: {
    enabled: false,
    apiKey: '',
    provider: 'twilio',
    smsTemplates: 'New complaint {{ticketNumber}} - Priority: {{priority}}. Description: {{description}}',
  },
  inApp: {
    enabled: true,
    notificationPreferences: 'all',
  },
  push: {
    enabled: false,
    firebaseApiKey: '',
    firebaseProjectId: '',
    firebaseMessagingSenderId: '',
    firebaseAppId: '',
  },
};

const CHANNEL_ICONS: Record<string, React.ElementType> = {
  whatsapp: MessageSquare,
  email: Mail,
  sms: Radio,
  inApp: Bell,
  push: Send,
};

const CHANNEL_LABELS: Record<string, string> = {
  whatsapp: 'WhatsApp',
  email: 'Email',
  sms: 'SMS',
  inApp: 'In-App Notifications',
  push: 'Push Notifications',
};

export default function OmnichannelSetup() {
  const { t } = useTranslation();
  const { toast } = useToast();
  const [config, setConfig] = useState<ChannelState>(defaultConfig);
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  const fetchConfig = useCallback(async () => {
    setLoading(true);
    try {
      const res = await authFetch('/api/settings?category=communication');
      if (res.ok) {
        const data = await res.json();
        const settings = data.settings || {};
        // Merge saved settings with defaults
        const merged = { ...defaultConfig };
        for (const channel of Object.keys(defaultConfig)) {
          if (settings[channel]) {
            try {
              const parsed = typeof settings[channel] === 'string' ? JSON.parse(settings[channel]) : settings[channel];
              merged[channel as keyof ChannelState] = { ...defaultConfig[channel as keyof ChannelState], ...parsed };
            } catch {
              // use defaults
            }
          }
        }
        setConfig(merged);
      }
    } catch (err) {
      console.error('Fetch config error:', err);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const updateChannel = (channel: keyof ChannelState, field: string, value: unknown) => {
    setConfig(prev => ({
      ...prev,
      [channel]: { ...prev[channel], [field]: value },
    }));
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const settings = Object.entries(config).map(([channel, data]) => ({
        key: `communication_${channel}`,
        value: JSON.stringify(data),
        category: 'communication',
      }));

      const res = await authFetch('/api/settings', {
        method: 'PUT',
        body: JSON.stringify({ settings }),
      });

      if (res.ok) {
        toast({ title: t.messages.success.saved });
      } else {
        toast({ title: t.messages.error.updateFailed, variant: 'destructive' });
      }
    } catch {
      toast({ title: t.messages.error.networkError, variant: 'destructive' });
    } finally {
      setSaving(false);
    }
  };

  const testConnection = async (channel: string) => {
    setTesting(channel);
    try {
      // Simulate test - in production this would actually test the connection
      await new Promise(resolve => setTimeout(resolve, 1500));
      toast({ title: `Test connection for ${CHANNEL_LABELS[channel]} completed`, description: 'Connection test simulated successfully' });
    } catch {
      toast({ title: `Test failed for ${CHANNEL_LABELS[channel]}`, variant: 'destructive' });
    } finally {
      setTesting(null);
    }
  };

  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 animate-fade-in">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <Settings className="w-6 h-6 text-emerald-600" />
            Omnichannel Communication
          </h1>
          <p className="text-sm text-muted-foreground mt-1">Configure communication channels for notifications and alerts</p>
        </div>
        <Button onClick={handleSave} disabled={saving} className="bg-emerald-600 hover:bg-emerald-700">
          {saving ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : <Save className="w-4 h-4 mr-2" />}
          Save Configuration
        </Button>
      </div>

      <div className="grid grid-cols-1 gap-4">
        {(['whatsapp', 'email', 'sms', 'inApp', 'push'] as const).map((channel) => {
          const Icon = CHANNEL_ICONS[channel];
          const channelConfig = config[channel];
          const isTesting = testing === channel;

          return (
            <Card key={channel} className={channelConfig.enabled ? 'border-emerald-200 dark:border-emerald-800' : ''}>
              <CardHeader className="pb-3">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${
                      channelConfig.enabled ? 'bg-emerald-100 dark:bg-emerald-900/30' : 'bg-muted'
                    }`}>
                      <Icon className={`w-5 h-5 ${channelConfig.enabled ? 'text-emerald-600' : 'text-muted-foreground'}`} />
                    </div>
                    <div>
                      <CardTitle className="text-base">{CHANNEL_LABELS[channel]}</CardTitle>
                      <CardDescription className="text-xs">
                        {channelConfig.enabled ? (
                          <span className="text-emerald-600 flex items-center gap-1">
                            <CheckCircle2 className="w-3 h-3" /> Active
                          </span>
                        ) : 'Disabled'}
                      </CardDescription>
                    </div>
                  </div>
                  <div className="flex items-center gap-3">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => testConnection(channel)}
                      disabled={!channelConfig.enabled || isTesting}
                      className="text-xs"
                    >
                      {isTesting ? <Loader2 className="w-3 h-3 animate-spin mr-1" /> : <TestTube className="w-3 h-3 mr-1" />}
                      Test
                    </Button>
                    <Switch
                      checked={channelConfig.enabled}
                      onCheckedChange={(checked) => updateChannel(channel, 'enabled', checked)}
                    />
                  </div>
                </div>
              </CardHeader>
              {channelConfig.enabled && (
                <CardContent className="space-y-4 pt-0">
                  {channel === 'whatsapp' && (
                    <>
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div className="space-y-1.5">
                          <Label className="text-xs">API Key</Label>
                          <Input
                            type="password"
                            value={String(channelConfig.apiKey || '')}
                            onChange={(e) => updateChannel(channel, 'apiKey', e.target.value)}
                            placeholder="Enter WhatsApp API key"
                          />
                        </div>
                        <div className="space-y-1.5">
                          <Label className="text-xs">Phone Number</Label>
                          <Input
                            value={String(channelConfig.phoneNumber || '')}
                            onChange={(e) => updateChannel(channel, 'phoneNumber', e.target.value)}
                            placeholder="+880..."
                          />
                        </div>
                      </div>
                      <div className="space-y-1.5">
                        <Label className="text-xs">Template Messages</Label>
                        <Textarea
                          value={String(channelConfig.templateMessages || '')}
                          onChange={(e) => updateChannel(channel, 'templateMessages', e.target.value)}
                          placeholder="Use {{ticketNumber}}, {{priority}}, {{name}} as placeholders"
                          rows={3}
                        />
                      </div>
                    </>
                  )}

                  {channel === 'email' && (
                    <>
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div className="space-y-1.5">
                          <Label className="text-xs">SMTP Host</Label>
                          <Input
                            value={String(channelConfig.smtpHost || '')}
                            onChange={(e) => updateChannel(channel, 'smtpHost', e.target.value)}
                            placeholder="smtp.example.com"
                          />
                        </div>
                        <div className="space-y-1.5">
                          <Label className="text-xs">SMTP Port</Label>
                          <Input
                            value={String(channelConfig.smtpPort || '')}
                            onChange={(e) => updateChannel(channel, 'smtpPort', e.target.value)}
                            placeholder="587"
                          />
                        </div>
                        <div className="space-y-1.5">
                          <Label className="text-xs">Username</Label>
                          <Input
                            value={String(channelConfig.smtpUsername || '')}
                            onChange={(e) => updateChannel(channel, 'smtpUsername', e.target.value)}
                            placeholder="user@example.com"
                          />
                        </div>
                        <div className="space-y-1.5">
                          <Label className="text-xs">Password</Label>
                          <Input
                            type="password"
                            value={String(channelConfig.smtpPassword || '')}
                            onChange={(e) => updateChannel(channel, 'smtpPassword', e.target.value)}
                            placeholder="SMTP password"
                          />
                        </div>
                      </div>
                      <div className="space-y-1.5">
                        <Label className="text-xs">Email Templates</Label>
                        <Textarea
                          value={String(channelConfig.emailTemplates || '')}
                          onChange={(e) => updateChannel(channel, 'emailTemplates', e.target.value)}
                          placeholder="Use {{ticketNumber}}, {{priority}}, {{name}}, {{description}} as placeholders"
                          rows={4}
                        />
                      </div>
                    </>
                  )}

                  {channel === 'sms' && (
                    <>
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div className="space-y-1.5">
                          <Label className="text-xs">API Key</Label>
                          <Input
                            type="password"
                            value={String(channelConfig.apiKey || '')}
                            onChange={(e) => updateChannel(channel, 'apiKey', e.target.value)}
                            placeholder="Enter SMS API key"
                          />
                        </div>
                        <div className="space-y-1.5">
                          <Label className="text-xs">Provider</Label>
                          <Input
                            value={String(channelConfig.provider || '')}
                            onChange={(e) => updateChannel(channel, 'provider', e.target.value)}
                            placeholder="e.g., twilio, vonage"
                          />
                        </div>
                      </div>
                      <div className="space-y-1.5">
                        <Label className="text-xs">SMS Templates</Label>
                        <Textarea
                          value={String(channelConfig.smsTemplates || '')}
                          onChange={(e) => updateChannel(channel, 'smsTemplates', e.target.value)}
                          placeholder="Use {{ticketNumber}}, {{priority}}, {{description}} as placeholders"
                          rows={3}
                        />
                      </div>
                    </>
                  )}

                  {channel === 'inApp' && (
                    <div className="space-y-1.5">
                      <Label className="text-xs">Notification Preferences</Label>
                      <Input
                        value={String(channelConfig.notificationPreferences || '')}
                        onChange={(e) => updateChannel(channel, 'notificationPreferences', e.target.value)}
                        placeholder="all, critical_only, assigned_only"
                      />
                      <p className="text-[10px] text-muted-foreground">Options: all, critical_only, assigned_only</p>
                    </div>
                  )}

                  {channel === 'push' && (
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                      <div className="space-y-1.5">
                        <Label className="text-xs">Firebase API Key</Label>
                        <Input
                          type="password"
                          value={String(channelConfig.firebaseApiKey || '')}
                          onChange={(e) => updateChannel(channel, 'firebaseApiKey', e.target.value)}
                          placeholder="AIza..."
                        />
                      </div>
                      <div className="space-y-1.5">
                        <Label className="text-xs">Firebase Project ID</Label>
                        <Input
                          value={String(channelConfig.firebaseProjectId || '')}
                          onChange={(e) => updateChannel(channel, 'firebaseProjectId', e.target.value)}
                          placeholder="your-project-id"
                        />
                      </div>
                      <div className="space-y-1.5">
                        <Label className="text-xs">Messaging Sender ID</Label>
                        <Input
                          value={String(channelConfig.firebaseMessagingSenderId || '')}
                          onChange={(e) => updateChannel(channel, 'firebaseMessagingSenderId', e.target.value)}
                          placeholder="123456789"
                        />
                      </div>
                      <div className="space-y-1.5">
                        <Label className="text-xs">Firebase App ID</Label>
                        <Input
                          value={String(channelConfig.firebaseAppId || '')}
                          onChange={(e) => updateChannel(channel, 'firebaseAppId', e.target.value)}
                          placeholder="1:123456789:web:abc"
                        />
                      </div>
                    </div>
                  )}
                </CardContent>
              )}
            </Card>
          );
        })}
      </div>
    </div>
  );
}
