
'use client';

import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent } from '@/components/ui/card';
import { toast } from 'sonner';
import { Calendar, RefreshCw, AlertCircle } from 'lucide-react';

interface CalendarSyncSettingsProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function CalendarSyncSettings({ open, onOpenChange }: CalendarSyncSettingsProps) {
  const [loading, setLoading] = useState(false);
  const [syncConfig, setSyncConfig] = useState<any>(null);
  const [formData, setFormData] = useState({
    provider: 'GOOGLE',
    isEnabled: true,
    syncDirection: 'ONE_WAY',
    autoSync: true,
    syncFrequency: '15'
  });

  useEffect(() => {
    if (open) {
      fetchSyncConfig();
    }
  }, [open]);

  const fetchSyncConfig = async () => {
    try {
      const response = await fetch('/api/calendar/sync');
      const data = await response.json();
      if (data.syncConfig) {
        setSyncConfig(data.syncConfig);
        setFormData({
          provider: data.syncConfig.provider,
          isEnabled: data.syncConfig.isEnabled,
          syncDirection: data.syncConfig.syncDirection,
          autoSync: data.syncConfig.autoSync,
          syncFrequency: data.syncConfig.syncFrequency.toString()
        });
      }
    } catch (error) {
      console.error('Error fetching sync config:', error);
    }
  };

  const handleSave = async () => {
    setLoading(true);
    try {
      const response = await fetch('/api/calendar/sync', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...formData,
          syncFrequency: parseInt(formData.syncFrequency)
        })
      });

      if (response.ok) {
        toast.success('Sync settings updated successfully');
        onOpenChange(false);
      } else {
        toast.error('Failed to update sync settings');
      }
    } catch (error) {
      console.error('Error saving sync settings:', error);
      toast.error('Error saving sync settings');
    } finally {
      setLoading(false);
    }
  };

  const handleConnectGoogle = async () => {
    try {
      const response = await fetch('/api/calendar/oauth/google');
      const data = await response.json();
      
      if (data.authUrl) {
        // Open OAuth window
        window.location.href = data.authUrl;
      } else {
        toast.error('Failed to initiate Google OAuth');
      }
    } catch (error) {
      console.error('Error connecting to Google:', error);
      toast.error('Error connecting to Google Calendar');
    }
  };

  const handleConnectMicrosoft = async () => {
    try {
      const response = await fetch('/api/calendar/oauth/microsoft');
      const data = await response.json();
      
      if (data.authUrl) {
        // Open OAuth window
        window.location.href = data.authUrl;
      } else {
        toast.error('Failed to initiate Microsoft OAuth');
      }
    } catch (error) {
      console.error('Error connecting to Microsoft:', error);
      toast.error('Error connecting to Microsoft Calendar');
    }
  };

  const handleSyncNow = async () => {
    setLoading(true);
    try {
      const response = await fetch('/api/calendar/sync-now', {
        method: 'POST',
      });

      if (response.ok) {
        const result = await response.json();
        toast.success(`Synced ${result.syncedCount} events successfully`, {
          description: result.conflictsDetected > 0 
            ? `Detected ${result.conflictsDetected} conflicts (CRM wins as source of truth)`
            : undefined,
        });
        fetchSyncConfig(); // Refresh config
      } else {
        const error = await response.json();
        toast.error(error.error || 'Failed to sync calendar');
      }
    } catch (error) {
      console.error('Error syncing calendar:', error);
      toast.error('Error syncing calendar');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Calendar className="w-5 h-5" />
            Calendar Sync Settings
          </DialogTitle>
          <DialogDescription>
            Configure 2-way calendar sync with Google Calendar or Microsoft Outlook.
            Your CRM calendar will remain the source of truth.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6">
          {/* MVP Notice */}
          <Card className="border-blue-200 bg-blue-50">
            <CardContent className="pt-4">
              <div className="flex items-start gap-2">
                <AlertCircle className="w-5 h-5 text-blue-600 mt-0.5" />
                <div className="text-sm">
                  <p className="font-semibold text-blue-900 mb-1">MVP Phase: ICS Export Available</p>
                  <p className="text-blue-800">
                    Currently supporting <strong>one-way sync</strong> via ICS export. 
                    Full 2-way sync with Google/Microsoft calendars will be enabled in the next release.
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>

          <div className="space-y-4">
            <div>
              <Label htmlFor="provider">Calendar Provider</Label>
              <Select
                value={formData.provider}
                onValueChange={(value) => setFormData({ ...formData, provider: value })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="GOOGLE">Google Calendar</SelectItem>
                  <SelectItem value="MICROSOFT">Microsoft Outlook</SelectItem>
                  <SelectItem value="ICS">ICS Export (Current)</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="flex items-center justify-between">
              <div>
                <Label htmlFor="isEnabled">Enable Sync</Label>
                <p className="text-sm text-muted-foreground">
                  Enable automatic calendar synchronization
                </p>
              </div>
              <Switch
                id="isEnabled"
                checked={formData.isEnabled}
                onCheckedChange={(checked) =>
                  setFormData({ ...formData, isEnabled: checked })
                }
              />
            </div>

            <div>
              <Label htmlFor="syncDirection">Sync Direction</Label>
              <Select
                value={formData.syncDirection}
                onValueChange={(value) =>
                  setFormData({ ...formData, syncDirection: value })
                }
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="ONE_WAY">
                    One-Way (CRM → External Calendar)
                  </SelectItem>
                  <SelectItem value="TWO_WAY">
                    Two-Way (Full Sync) ✅ Available Now!
                  </SelectItem>
                </SelectContent>
              </Select>
              <p className="text-xs text-muted-foreground mt-1">
                One-way sync pushes CRM events to your calendar. Two-way sync prevents double bookings and syncs changes both ways.
              </p>
            </div>

            {/* OAuth Connection Buttons */}
            <div className="space-y-3 pt-4 border-t">
              <Label>Connect External Calendar</Label>
              <p className="text-sm text-muted-foreground">
                Connect your calendar to enable automatic synchronization
              </p>
              
              <div className="flex flex-col gap-2">
                <Button
                  type="button"
                  variant="outline"
                  className="w-full justify-start"
                  onClick={handleConnectGoogle}
                >
                  <svg className="w-5 h-5 mr-2" viewBox="0 0 24 24">
                    <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
                    <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
                    <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/>
                    <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
                  </svg>
                  {syncConfig?.provider === 'GOOGLE' && syncConfig?.accessToken ? (
                    <span>✅ Connected to Google Calendar</span>
                  ) : (
                    <span>Connect Google Calendar</span>
                  )}
                </Button>

                <Button
                  type="button"
                  variant="outline"
                  className="w-full justify-start"
                  onClick={handleConnectMicrosoft}
                >
                  <svg className="w-5 h-5 mr-2" viewBox="0 0 24 24">
                    <path fill="#f25022" d="M1 1h10v10H1z"/>
                    <path fill="#00a4ef" d="M13 1h10v10H13z"/>
                    <path fill="#7fba00" d="M1 13h10v10H1z"/>
                    <path fill="#ffb900" d="M13 13h10v10H13z"/>
                  </svg>
                  {syncConfig?.provider === 'MICROSOFT' && syncConfig?.accessToken ? (
                    <span>✅ Connected to Microsoft Outlook</span>
                  ) : (
                    <span>Connect Microsoft Outlook</span>
                  )}
                </Button>
              </div>
            </div>

            {/* Sync Now Button */}
            {syncConfig?.accessToken && (
              <div className="pt-4 border-t">
                <Button
                  type="button"
                  variant="default"
                  className="w-full"
                  onClick={handleSyncNow}
                  disabled={loading}
                >
                  <RefreshCw className={`w-4 h-4 mr-2 ${loading ? 'animate-spin' : ''}`} />
                  Sync Now
                </Button>
                <p className="text-xs text-muted-foreground mt-2 text-center">
                  Last synced: {syncConfig.lastSyncedAt 
                    ? new Date(syncConfig.lastSyncedAt).toLocaleString() 
                    : 'Never'}
                </p>
              </div>
            )}

            <div className="flex items-center justify-between">
              <div>
                <Label htmlFor="autoSync">Auto Sync</Label>
                <p className="text-sm text-muted-foreground">
                  Automatically sync changes in real-time
                </p>
              </div>
              <Switch
                id="autoSync"
                checked={formData.autoSync}
                onCheckedChange={(checked) =>
                  setFormData({ ...formData, autoSync: checked })
                }
              />
            </div>

            {syncConfig && (
              <div className="pt-4 border-t">
                <h4 className="font-semibold mb-2">Sync Status</h4>
                <div className="space-y-2">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-muted-foreground">Last Synced:</span>
                    <span>
                      {syncConfig.lastSyncedAt
                        ? new Date(syncConfig.lastSyncedAt).toLocaleString()
                        : 'Never'}
                    </span>
                  </div>
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-muted-foreground">Status:</span>
                    <Badge variant={syncConfig.isEnabled ? 'default' : 'secondary'}>
                      {syncConfig.isEnabled ? 'Enabled' : 'Disabled'}
                    </Badge>
                  </div>
                </div>
              </div>
            )}
          </div>

          <div className="flex justify-end gap-2 pt-4 border-t">
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
            <Button onClick={handleSave} disabled={loading}>
              {loading ? 'Saving...' : 'Save Settings'}
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
