'use client';

import { useState, useEffect, useCallback } from 'react';
import { useSession, signOut } from 'next-auth/react';
import api from '@/services/api';

interface PrivacySetting {
  id: string;
  label: string;
  description: string;
  value: string;
  options: { value: string; label: string }[];
}

interface PrivacyFormProps {
  onSave?: (data: {
    privacySettings: PrivacySetting[];
    dataSettings: {
      shareAnalytics: boolean;
      personalizedAds: boolean;
      thirdPartySharing: boolean;
    };
  }) => void;
  onDeleteAccount?: () => void;
}

// Default privacy settings
const DEFAULT_PRIVACY_SETTINGS: PrivacySetting[] = [
  {
    id: 'profile_visibility',
    label: 'Profile Visibility',
    description: 'Control who can see your profile',
    value: 'public',
    options: [
      { value: 'public', label: 'Public' },
      { value: 'connections', label: 'Connections Only' },
      { value: 'private', label: 'Private' },
    ],
  },
  {
    id: 'contact_info',
    label: 'Contact Information',
    description: 'Control who can see your contact details',
    value: 'connections',
    options: [
      { value: 'public', label: 'Public' },
      { value: 'connections', label: 'Connections Only' },
      { value: 'private', label: 'Hidden' },
    ],
  },
  {
    id: 'activity_status',
    label: 'Activity Status',
    description: 'Show when you are active on the platform',
    value: 'public',
    options: [
      { value: 'public', label: 'Everyone' },
      { value: 'connections', label: 'Connections Only' },
      { value: 'private', label: 'No One' },
    ],
  },
];

const DEFAULT_DATA_SETTINGS = {
  shareAnalytics: false,
  personalizedAds: false,
  thirdPartySharing: false,
};

export function PrivacyForm({ onSave, onDeleteAccount }: PrivacyFormProps) {
  const { data: session } = useSession();
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  const [privacySettings, setPrivacySettings] = useState<PrivacySetting[]>(DEFAULT_PRIVACY_SETTINGS);
  const [dataSettings, setDataSettings] = useState(DEFAULT_DATA_SETTINGS);

  // Fetch saved preferences on mount
  const fetchPreferences = useCallback(async () => {
    if (!session) return;

    try {
      setIsLoading(true);
      const role = (session?.user as any)?.role;
      const endpoint = role === 'AGENT' ? '/agents/preferences/privacy' : '/users/preferences/privacy';

      const response = await api.get(endpoint);
      const savedPrefs = response.data?.data || response.data || {};

      // Merge saved privacy settings with defaults
      if (savedPrefs.privacySettings) {
        setPrivacySettings((prev) =>
          prev.map((item) => ({
            ...item,
            value: savedPrefs.privacySettings[item.id] ?? item.value,
          }))
        );
      }

      // Merge saved data settings with defaults
      if (savedPrefs.dataSettings) {
        setDataSettings((prev) => ({
          shareAnalytics: savedPrefs.dataSettings.shareAnalytics ?? prev.shareAnalytics,
          personalizedAds: savedPrefs.dataSettings.personalizedAds ?? prev.personalizedAds,
          thirdPartySharing: savedPrefs.dataSettings.thirdPartySharing ?? prev.thirdPartySharing,
        }));
      }
    } catch (err) {
      // If no saved preferences, use defaults
      console.log('No saved privacy preferences found, using defaults');
    } finally {
      setIsLoading(false);
    }
  }, [session]);

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

  const handlePrivacyChange = (id: string, value: string) => {
    setPrivacySettings((prev) =>
      prev.map((item) => (item.id === id ? { ...item, value } : item))
    );
  };

  const handleDataSettingChange = (key: keyof typeof dataSettings) => {
    setDataSettings((prev) => ({ ...prev, [key]: !prev[key] }));
  };

  const handleSave = async () => {
    setIsSaving(true);
    setError(null);
    setSuccess(null);

    try {
      const role = (session?.user as any)?.role;
      const endpoint = role === 'AGENT' ? '/agents/preferences/privacy' : '/users/preferences/privacy';

      // Transform settings to API format
      const preferences = {
        privacySettings: privacySettings.reduce(
          (acc, item) => ({ ...acc, [item.id]: item.value }),
          {} as Record<string, string>
        ),
        dataSettings,
      };

      await api.put(endpoint, preferences);

      setSuccess('Privacy settings saved successfully!');

      if (onSave) {
        onSave({ privacySettings, dataSettings });
      }

      // Clear success message after 3 seconds
      setTimeout(() => setSuccess(null), 3000);
    } catch (err: unknown) {
      const error = err as { response?: { data?: { message?: string } } };
      setError(error.response?.data?.message || 'Failed to save privacy settings. Please try again.');
    } finally {
      setIsSaving(false);
    }
  };

  const handleDeleteAccount = async () => {
    if (!confirm('Are you sure you want to delete your account? This action cannot be undone.')) {
      return;
    }

    // Double confirmation for safety
    if (!confirm('This will permanently delete all your data. Are you absolutely sure?')) {
      return;
    }

    setIsDeleting(true);
    setError(null);

    try {
      const role = (session?.user as any)?.role;
      const endpoint = role === 'AGENT' ? '/agents/account' : '/users/account';

      await api.delete(endpoint);

      // Call the optional callback
      if (onDeleteAccount) {
        onDeleteAccount();
      }

      // Sign out and redirect to home page
      await signOut({ callbackUrl: '/' });
    } catch (err: unknown) {
      const error = err as { response?: { data?: { message?: string } } };
      setError(error.response?.data?.message || 'Failed to delete account. Please try again.');
      setIsDeleting(false);
    }
  };

  const ToggleSwitch = ({
    enabled,
    onToggle,
  }: {
    enabled: boolean;
    onToggle: () => void;
  }) => (
    <button
      onClick={onToggle}
      className={`relative w-[44px] h-[24px] rounded-full transition-colors cursor-pointer ${
        enabled ? 'bg-[#e58625]' : 'bg-[#00293D]/20'
      }`}
    >
      <div
        className={`absolute top-[2px] w-[20px] h-[20px] rounded-full bg-white shadow transition-transform ${
          enabled ? 'translate-x-[22px]' : 'translate-x-[2px]'
        }`}
      />
    </button>
  );

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#e58625]"></div>
      </div>
    );
  }

  const role = (session?.user as any)?.role;
  const isAgent = role === 'AGENT';

  // Filter settings: Profile Visibility only for agents, Activity Status for both
  const visibleSettings = privacySettings.filter((item) => {
    if (item.id === 'profile_visibility') return isAgent;
    if (item.id === 'activity_status') return true;
    return false;
  });

  return (
    <>
      {/* Error Message */}
      {error && (
        <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-[10px] text-red-700 text-[13px] font-serif">
          {error}
        </div>
      )}

      {/* Success Message */}
      {success && (
        <div className="mb-4 p-3 bg-green-50 border border-green-200 rounded-[10px] text-green-700 text-[13px] font-serif">
          {success}
        </div>
      )}

      {/* Privacy Settings */}
      {visibleSettings.length > 0 && (
        <div className="border border-[#00293d]/10 rounded-[15px] bg-white p-6 mb-4">
          <div className="mb-6">
            <h2 className="font-fractul font-bold text-[16px] text-[#00293D] mb-2">
              Privacy Settings
            </h2>
            <p className="font-serif text-[12px] text-[#00293D]/60">
              Control your privacy and visibility preferences
            </p>
          </div>

          <div className="space-y-6">
            {visibleSettings.map((item) => (
              <div
                key={item.id}
                className="pb-4 border-b border-[#00293d]/10 last:border-0"
              >
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                  <div>
                    <h3 className="font-serif font-medium text-[14px] text-[#00293D]">
                      {item.label}
                    </h3>
                    <p className="font-serif text-[12px] text-[#00293D]/60">
                      {item.description}
                    </p>
                  </div>
                  <select
                    value={item.value}
                    onChange={(e) => handlePrivacyChange(item.id, e.target.value)}
                    className="h-[36px] px-4 border border-[#00293D]/20 rounded-[10px] text-[13px] font-serif text-[#00293D] focus:outline-none focus:border-[#E58625] bg-white cursor-pointer"
                  >
                    {item.options.map((option) => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
            ))}
          </div>

          {/* Save Button */}
          <div className="flex justify-end mt-6">
            <button
              onClick={handleSave}
              disabled={isSaving}
              className="px-8 py-3 bg-[#e58625] text-white rounded-[15px] font-fractul font-medium text-[14px] hover:bg-[#d47920] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isSaving ? 'Saving...' : 'Save Changes'}
            </button>
          </div>
        </div>
      )}

      {/* Delete Account */}
      <div className="border border-[#00293d]/10 rounded-[15px] bg-white p-6">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div>
            <h3 className="font-serif font-medium text-[14px] text-[#00293D]">
              Delete Account
            </h3>
            <p className="font-serif text-[12px] text-[#00293D]/60">
              Permanently delete your account and all data
            </p>
          </div>
          <button
            onClick={handleDeleteAccount}
            disabled={isDeleting}
            className="px-6 py-2 border border-red-500 text-red-500 rounded-[15px] font-serif text-[12px] hover:bg-red-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isDeleting ? 'Deleting...' : 'Delete Account'}
          </button>
        </div>
      </div>
    </>
  );
}
