"use client";

import { useState, useTransition } from "react";
import Link from "next/link";

interface PrivacySettings {
  profileVisibility: "public" | "contacts" | "private";
  showEmail: boolean;
  showPhone: boolean;
  showLocation: boolean;
  showOnlineStatus: boolean;
  allowDirectMessages: boolean;
  allowGroupInvites: boolean;
  allowMentions: boolean;
  allowAnalytics: boolean;
  allowPersonalization: boolean;
  allowThirdPartyIntegrations: boolean;
  emailMarketing: boolean;
  emailProductUpdates: boolean;
  emailSecurityAlerts: boolean;
  emailActivityDigest: boolean;
  activityHistoryRetention: "30d" | "90d" | "1y" | "forever";
  searchHistoryEnabled: boolean;
  twoFactorEnabled: boolean;
  loginNotifications: boolean;
  sessionTimeout: number;
}

const defaultSettings: PrivacySettings = {
  profileVisibility: "contacts",
  showEmail: false,
  showPhone: false,
  showLocation: true,
  showOnlineStatus: true,
  allowDirectMessages: true,
  allowGroupInvites: true,
  allowMentions: true,
  allowAnalytics: true,
  allowPersonalization: true,
  allowThirdPartyIntegrations: false,
  emailMarketing: false,
  emailProductUpdates: true,
  emailSecurityAlerts: true,
  emailActivityDigest: true,
  activityHistoryRetention: "90d",
  searchHistoryEnabled: true,
  twoFactorEnabled: false,
  loginNotifications: true,
  sessionTimeout: 60,
};

interface UserPrivacyProps {
  initialSettings?: Record<string, unknown>;
}

export default function UserPrivacy({ initialSettings }: UserPrivacyProps) {
  const [isPending, startTransition] = useTransition();
  const [settings, setSettings] = useState<PrivacySettings>(() => {
    if (!initialSettings) return defaultSettings;
    return {
      ...defaultSettings,
      ...Object.fromEntries(
        Object.entries(initialSettings).filter(([k]) => k in defaultSettings)
      ),
    } as PrivacySettings;
  });
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const [activeSection, setActiveSection] = useState<string | null>(null);

  const updateSetting = <K extends keyof PrivacySettings>(key: K, value: PrivacySettings[K]) => {
    setSettings((prev) => ({ ...prev, [key]: value }));
  };

  const handleSave = () => {
    startTransition(async () => {
      try {
        const { savePrivacySettings } = await import("@/app/actions/privacy");
        const result = await savePrivacySettings(settings as unknown as Record<string, unknown>);
        if (result.error) {
          setMessage({ type: "error", text: result.error });
        } else {
          setMessage({ type: "success", text: result.message || "Privacy settings saved successfully." });
        }
      } catch {
        setMessage({ type: "error", text: "Failed to save privacy settings." });
      }
      setTimeout(() => setMessage(null), 5000);
    });
  };

  const handleExportData = () => {
    setMessage({ type: "success", text: "Data export request submitted. You will receive an email when ready." });
    setTimeout(() => setMessage(null), 5000);
  };

  const SettingSwitch = ({
    label,
    description,
    checked,
    onChange,
  }: {
    label: string;
    description?: string;
    checked: boolean;
    onChange: (checked: boolean) => void;
  }) => (
    <div className="d-flex justify-content-between align-items-start py-3 border-bottom">
      <div className="me-3">
        <div className="fw-medium">{label}</div>
        {description && <small className="text-muted">{description}</small>}
      </div>
      <label className="form-check form-switch mb-0">
        <input
          type="checkbox"
          className="form-check-input"
          checked={checked}
          onChange={(e) => onChange(e.target.checked)}
        />
      </label>
    </div>
  );

  const privacyScore = (() => {
    let score = 50;
    if (settings.profileVisibility === "private") score += 15;
    else if (settings.profileVisibility === "contacts") score += 10;
    if (!settings.showEmail) score += 5;
    if (!settings.showPhone) score += 5;
    if (settings.twoFactorEnabled) score += 15;
    if (!settings.allowThirdPartyIntegrations) score += 5;
    if (!settings.emailMarketing) score += 5;
    return Math.min(score, 100);
  })();

  return (
    <>
      {/* Page Header */}
      <div className="d-flex align-items-center justify-content-between mb-4">
        <div className="d-flex align-items-center">
          <Link href="/" className="btn btn-light btn-sm me-3">
            <i className="ph-arrow-left"></i>
          </Link>
          <div>
            <h4 className="mb-0">
              <i className="ph-lock me-2"></i>
              Privacy Settings
            </h4>
            <p className="text-muted mb-0 mt-1">Control your privacy, data sharing preferences, and communication settings.</p>
          </div>
        </div>
        <button className="btn btn-primary" onClick={handleSave} disabled={isPending}>
          {isPending ? (
            <>
              <span className="spinner-border spinner-border-sm me-2"></span>
              Saving...
            </>
          ) : (
            <>
              <i className="ph-floppy-disk me-2"></i>
              Save Changes
            </>
          )}
        </button>
      </div>

      {/* Alert */}
      {message && (
        <div
          className={`alert ${message.type === "success" ? "alert-success" : "alert-danger"} alert-dismissible`}
          role="alert"
        >
          <i className={`ph-${message.type === "success" ? "check-circle" : "warning"} me-2`}></i>
          {message.text}
          <button type="button" className="btn-close" onClick={() => setMessage(null)}></button>
        </div>
      )}

      <div className="row">
        {/* Left Column - Settings */}
        <div className="col-xl-8">
          {/* Profile Visibility */}
          <div className="card">
            <div
              className="card-header d-flex align-items-center"
              onClick={() => setActiveSection(activeSection === "profile" ? null : "profile")}
              style={{ cursor: "pointer" }}
            >
              <i className="ph-user-circle me-2 text-primary"></i>
              <h5 className="mb-0 flex-fill">Profile Visibility</h5>
              <i className={`ph-caret-${activeSection === "profile" ? "up" : "down"}`}></i>
            </div>
            <div className={`card-body ${activeSection !== null && activeSection !== "profile" ? "d-none" : ""}`}>
              <div className="mb-4">
                <label className="form-label">Who can see your profile?</label>
                <div className="d-flex gap-2 flex-wrap">
                  {[
                    { value: "public", label: "Everyone", icon: "ph-globe", desc: "Visible to all users" },
                    { value: "contacts", label: "Contacts Only", icon: "ph-users", desc: "Only your contacts" },
                    { value: "private", label: "Private", icon: "ph-lock", desc: "Only you" },
                  ].map((option) => (
                    <div
                      key={option.value}
                      className={`card flex-fill ${settings.profileVisibility === option.value ? "border-primary" : ""}`}
                      style={{ cursor: "pointer", minWidth: "150px" }}
                      onClick={() => updateSetting("profileVisibility", option.value as "public" | "contacts" | "private")}
                    >
                      <div className="card-body text-center py-3">
                        <i className={`${option.icon} fs-2 ${settings.profileVisibility === option.value ? "text-primary" : "text-muted"} mb-2 d-block`}></i>
                        <div className="fw-medium">{option.label}</div>
                        <small className="text-muted">{option.desc}</small>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              <SettingSwitch
                label="Show email address"
                description="Allow others to see your email address on your profile"
                checked={settings.showEmail}
                onChange={(v) => updateSetting("showEmail", v)}
              />
              <SettingSwitch
                label="Show phone number"
                description="Allow others to see your phone number on your profile"
                checked={settings.showPhone}
                onChange={(v) => updateSetting("showPhone", v)}
              />
              <SettingSwitch
                label="Show location"
                description="Display your location on your profile"
                checked={settings.showLocation}
                onChange={(v) => updateSetting("showLocation", v)}
              />
              <SettingSwitch
                label="Show online status"
                description="Let others see when you're online"
                checked={settings.showOnlineStatus}
                onChange={(v) => updateSetting("showOnlineStatus", v)}
              />
            </div>
          </div>

          {/* Communication */}
          <div className="card">
            <div
              className="card-header d-flex align-items-center"
              onClick={() => setActiveSection(activeSection === "communication" ? null : "communication")}
              style={{ cursor: "pointer" }}
            >
              <i className="ph-chats me-2 text-success"></i>
              <h5 className="mb-0 flex-fill">Communication</h5>
              <i className={`ph-caret-${activeSection === "communication" ? "up" : "down"}`}></i>
            </div>
            <div className={`card-body ${activeSection !== null && activeSection !== "communication" ? "d-none" : ""}`}>
              <SettingSwitch
                label="Allow direct messages"
                description="Let other users send you direct messages"
                checked={settings.allowDirectMessages}
                onChange={(v) => updateSetting("allowDirectMessages", v)}
              />
              <SettingSwitch
                label="Allow group invites"
                description="Let others invite you to groups and channels"
                checked={settings.allowGroupInvites}
                onChange={(v) => updateSetting("allowGroupInvites", v)}
              />
              <SettingSwitch
                label="Allow @mentions"
                description="Let others mention you in messages and comments"
                checked={settings.allowMentions}
                onChange={(v) => updateSetting("allowMentions", v)}
              />
            </div>
          </div>

          {/* Data & Tracking */}
          <div className="card">
            <div
              className="card-header d-flex align-items-center"
              onClick={() => setActiveSection(activeSection === "data" ? null : "data")}
              style={{ cursor: "pointer" }}
            >
              <i className="ph-chart-line me-2 text-info"></i>
              <h5 className="mb-0 flex-fill">Data & Tracking</h5>
              <i className={`ph-caret-${activeSection === "data" ? "up" : "down"}`}></i>
            </div>
            <div className={`card-body ${activeSection !== null && activeSection !== "data" ? "d-none" : ""}`}>
              <SettingSwitch
                label="Usage analytics"
                description="Help us improve by sharing anonymous usage data"
                checked={settings.allowAnalytics}
                onChange={(v) => updateSetting("allowAnalytics", v)}
              />
              <SettingSwitch
                label="Personalization"
                description="Allow personalized recommendations based on your activity"
                checked={settings.allowPersonalization}
                onChange={(v) => updateSetting("allowPersonalization", v)}
              />
              <SettingSwitch
                label="Third-party integrations"
                description="Allow connected apps to access your data"
                checked={settings.allowThirdPartyIntegrations}
                onChange={(v) => updateSetting("allowThirdPartyIntegrations", v)}
              />

              <div className="mt-4 pt-3 border-top">
                <label className="form-label">Activity history retention</label>
                <select
                  className="form-select"
                  value={settings.activityHistoryRetention}
                  onChange={(e) => updateSetting("activityHistoryRetention", e.target.value as "30d" | "90d" | "1y" | "forever")}
                >
                  <option value="30d">30 days</option>
                  <option value="90d">90 days</option>
                  <option value="1y">1 year</option>
                  <option value="forever">Keep forever</option>
                </select>
                <small className="form-text text-muted">How long to keep your activity history</small>
              </div>

              <SettingSwitch
                label="Search history"
                description="Save your search history for better suggestions"
                checked={settings.searchHistoryEnabled}
                onChange={(v) => updateSetting("searchHistoryEnabled", v)}
              />
            </div>
          </div>

          {/* Email Preferences */}
          <div className="card">
            <div
              className="card-header d-flex align-items-center"
              onClick={() => setActiveSection(activeSection === "email" ? null : "email")}
              style={{ cursor: "pointer" }}
            >
              <i className="ph-envelope me-2 text-warning"></i>
              <h5 className="mb-0 flex-fill">Email Preferences</h5>
              <i className={`ph-caret-${activeSection === "email" ? "up" : "down"}`}></i>
            </div>
            <div className={`card-body ${activeSection !== null && activeSection !== "email" ? "d-none" : ""}`}>
              <SettingSwitch
                label="Marketing emails"
                description="Receive promotional emails and special offers"
                checked={settings.emailMarketing}
                onChange={(v) => updateSetting("emailMarketing", v)}
              />
              <SettingSwitch
                label="Product updates"
                description="Get notified about new features and improvements"
                checked={settings.emailProductUpdates}
                onChange={(v) => updateSetting("emailProductUpdates", v)}
              />
              <SettingSwitch
                label="Security alerts"
                description="Important notifications about your account security"
                checked={settings.emailSecurityAlerts}
                onChange={(v) => updateSetting("emailSecurityAlerts", v)}
              />
              <SettingSwitch
                label="Activity digest"
                description="Weekly summary of activity in your organization"
                checked={settings.emailActivityDigest}
                onChange={(v) => updateSetting("emailActivityDigest", v)}
              />
            </div>
          </div>

          {/* Security & Login */}
          <div className="card">
            <div
              className="card-header d-flex align-items-center"
              onClick={() => setActiveSection(activeSection === "security" ? null : "security")}
              style={{ cursor: "pointer" }}
            >
              <i className="ph-shield-check me-2 text-danger"></i>
              <h5 className="mb-0 flex-fill">Security & Login</h5>
              <i className={`ph-caret-${activeSection === "security" ? "up" : "down"}`}></i>
            </div>
            <div className={`card-body ${activeSection !== null && activeSection !== "security" ? "d-none" : ""}`}>
              <SettingSwitch
                label="Two-factor authentication"
                description="Add an extra layer of security to your account"
                checked={settings.twoFactorEnabled}
                onChange={(v) => updateSetting("twoFactorEnabled", v)}
              />
              <SettingSwitch
                label="Login notifications"
                description="Get notified when someone logs into your account"
                checked={settings.loginNotifications}
                onChange={(v) => updateSetting("loginNotifications", v)}
              />

              <div className="mt-4 pt-3 border-top">
                <label className="form-label">Session timeout</label>
                <select
                  className="form-select"
                  value={settings.sessionTimeout}
                  onChange={(e) => updateSetting("sessionTimeout", parseInt(e.target.value))}
                >
                  <option value="15">15 minutes</option>
                  <option value="30">30 minutes</option>
                  <option value="60">1 hour</option>
                  <option value="120">2 hours</option>
                  <option value="480">8 hours</option>
                  <option value="1440">24 hours</option>
                </select>
                <small className="form-text text-muted">Automatically log out after inactivity</small>
              </div>
            </div>
          </div>
        </div>

        {/* Right Column */}
        <div className="col-xl-4">
          {/* Privacy Score */}
          <div className="card">
            <div className="card-header">
              <h5 className="mb-0">
                <i className="ph-shield me-2"></i>
                Privacy Score
              </h5>
            </div>
            <div className="card-body text-center">
              <div className="position-relative d-inline-block mb-3">
                <div
                  className={`rounded-circle bg-${privacyScore >= 80 ? "success" : privacyScore >= 60 ? "warning" : "danger"} bg-opacity-10 d-flex align-items-center justify-content-center`}
                  style={{ width: "120px", height: "120px" }}
                >
                  <div>
                    <h2 className={`mb-0 text-${privacyScore >= 80 ? "success" : privacyScore >= 60 ? "warning" : "danger"}`}>
                      {privacyScore}%
                    </h2>
                    <small className="text-muted">Score</small>
                  </div>
                </div>
              </div>
              <p className="text-muted mb-0">
                {privacyScore >= 80
                  ? "Your privacy settings are well configured."
                  : "Consider tightening your privacy settings for better protection."}
              </p>
            </div>
          </div>

          {/* Data Management */}
          <div className="card">
            <div className="card-header">
              <h5 className="mb-0">
                <i className="ph-database me-2"></i>
                Data Management
              </h5>
            </div>
            <div className="card-body">
              <p className="text-muted mb-3">Download or manage your personal data stored in our systems.</p>
              <div className="d-grid gap-2">
                <button className="btn btn-outline-primary" onClick={handleExportData}>
                  <i className="ph-download me-2"></i>
                  Export My Data
                </button>
                <button className="btn btn-outline-secondary">
                  <i className="ph-eye me-2"></i>
                  View Stored Data
                </button>
              </div>
            </div>
          </div>

        </div>
      </div>
    </>
  );
}
