"use client";

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

interface AccountSettingsState {
  language: string;
  timezone: string;
  dateFormat: string;
  theme: "light" | "dark" | "system";
  notifyEmail: boolean;
  notifyBrowser: boolean;
  notifyActivity: boolean;
  notifySecurityAlerts: boolean;
  notifyProductUpdates: boolean;
  compactMode: boolean;
  showWelcomeScreen: boolean;
  defaultLandingPage: string;
  // Email settings (from gscWorkplace)
  messagesPerPage: string;
  defaultReplyMode: string;
  emailSignature: string;
  composeFormat: string;
  readReceipts: boolean;
  // Calendar settings (from gscWorkplace)
  calendarDefaultView: string;
  weekStartsOn: string;
  workingHoursStart: string;
  workingHoursEnd: string;
  defaultReminder: string;
  defaultEventDuration: string;
}

const defaultSettings: AccountSettingsState = {
  language: "en",
  timezone: "Europe/Helsinki",
  dateFormat: "DD/MM/YYYY",
  theme: "light",
  notifyEmail: true,
  notifyBrowser: true,
  notifyActivity: true,
  notifySecurityAlerts: true,
  notifyProductUpdates: false,
  compactMode: false,
  showWelcomeScreen: true,
  defaultLandingPage: "/",
  // Email defaults
  messagesPerPage: "50",
  defaultReplyMode: "reply",
  emailSignature: "",
  composeFormat: "html",
  readReceipts: true,
  // Calendar defaults
  calendarDefaultView: "week",
  weekStartsOn: "monday",
  workingHoursStart: "08:00",
  workingHoursEnd: "17:00",
  defaultReminder: "15",
  defaultEventDuration: "60",
};

interface AccountSettingsProps {
  displayName: string;
  email: string;
  initialSettings?: Record<string, unknown>;
}

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

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

  const handleSave = () => {
    startTransition(async () => {
      try {
        const { saveAccountSettings } = await import("@/app/actions/settings");
        const result = await saveAccountSettings(settings as unknown as Record<string, unknown>);
        if (result.error) {
          setMessage({ type: "error", text: result.error });
        } else {
          setMessage({ type: "success", text: result.message || "Settings saved successfully." });
        }
      } catch {
        setMessage({ type: "error", text: "Failed to save settings." });
      }
      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>
  );

  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-gear me-2"></i>
              Account Settings
            </h4>
            <p className="text-muted mb-0 mt-1">Manage your account preferences and display 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">
          {/* General Settings */}
          <div className="card">
            <div
              className="card-header d-flex align-items-center"
              onClick={() => setActiveSection(activeSection === "general" ? null : "general")}
              style={{ cursor: "pointer" }}
            >
              <i className="ph-sliders-horizontal me-2 text-primary"></i>
              <h5 className="mb-0 flex-fill">General</h5>
              <i className={`ph-caret-${activeSection === "general" ? "up" : "down"}`}></i>
            </div>
            <div className={`card-body ${activeSection !== null && activeSection !== "general" ? "d-none" : ""}`}>
              <div className="row g-3">
                <div className="col-md-6">
                  <label className="form-label">Language</label>
                  <select
                    className="form-select"
                    value={settings.language}
                    onChange={(e) => updateSetting("language", e.target.value)}
                  >
                    <option value="en">English</option>
                    <option value="de">Deutsch</option>
                    <option value="fr">Fran&ccedil;ais</option>
                  </select>
                  <small className="form-text text-muted">Display language for the portal interface</small>
                </div>
                <div className="col-md-6">
                  <label className="form-label">Timezone</label>
                  <select
                    className="form-select"
                    value={settings.timezone}
                    onChange={(e) => updateSetting("timezone", e.target.value)}
                  >
                    <option value="Europe/Helsinki">Europe/Helsinki (EET)</option>
                    <option value="Europe/Berlin">Europe/Berlin (CET)</option>
                    <option value="Europe/London">Europe/London (GMT)</option>
                    <option value="America/New_York">America/New York (EST)</option>
                    <option value="America/Los_Angeles">America/Los Angeles (PST)</option>
                    <option value="Asia/Tokyo">Asia/Tokyo (JST)</option>
                    <option value="UTC">UTC</option>
                  </select>
                  <small className="form-text text-muted">Used for timestamps and scheduling</small>
                </div>
                <div className="col-md-6">
                  <label className="form-label">Date Format</label>
                  <select
                    className="form-select"
                    value={settings.dateFormat}
                    onChange={(e) => updateSetting("dateFormat", e.target.value)}
                  >
                    <option value="DD/MM/YYYY">DD/MM/YYYY</option>
                    <option value="MM/DD/YYYY">MM/DD/YYYY</option>
                    <option value="YYYY-MM-DD">YYYY-MM-DD (ISO)</option>
                  </select>
                </div>
                <div className="col-md-6">
                  <label className="form-label">Default Landing Page</label>
                  <select
                    className="form-select"
                    value={settings.defaultLandingPage}
                    onChange={(e) => updateSetting("defaultLandingPage", e.target.value)}
                  >
                    <option value="/">Dashboard</option>
                    <option value="/marketplace">Marketplace</option>
                    <option value="/account/profile">Profile</option>
                  </select>
                </div>
              </div>
            </div>
          </div>

          {/* Appearance */}
          <div className="card">
            <div
              className="card-header d-flex align-items-center"
              onClick={() => setActiveSection(activeSection === "appearance" ? null : "appearance")}
              style={{ cursor: "pointer" }}
            >
              <i className="ph-palette me-2 text-info"></i>
              <h5 className="mb-0 flex-fill">Appearance</h5>
              <i className={`ph-caret-${activeSection === "appearance" ? "up" : "down"}`}></i>
            </div>
            <div className={`card-body ${activeSection !== null && activeSection !== "appearance" ? "d-none" : ""}`}>
              <label className="form-label mb-3">Theme</label>
              <div className="d-flex gap-2 flex-wrap mb-4">
                {[
                  { value: "light", label: "Light", icon: "ph-sun", desc: "Light background" },
                  { value: "dark", label: "Dark", icon: "ph-moon", desc: "Dark background" },
                  { value: "system", label: "System", icon: "ph-monitor", desc: "Match OS setting" },
                ].map((option) => (
                  <div
                    key={option.value}
                    className={`card flex-fill ${settings.theme === option.value ? "border-primary" : ""}`}
                    style={{ cursor: "pointer", minWidth: "140px" }}
                    onClick={() => updateSetting("theme", option.value as "light" | "dark" | "system")}
                  >
                    <div className="card-body text-center py-3">
                      <i className={`${option.icon} fs-2 ${settings.theme === 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>

              <SettingSwitch
                label="Compact mode"
                description="Reduce spacing for a more condensed layout"
                checked={settings.compactMode}
                onChange={(v) => updateSetting("compactMode", v)}
              />
              <SettingSwitch
                label="Show welcome screen"
                description="Display the welcome greeting on the dashboard"
                checked={settings.showWelcomeScreen}
                onChange={(v) => updateSetting("showWelcomeScreen", v)}
              />
            </div>
          </div>

          {/* Email Display Settings */}
          <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-success"></i>
              <h5 className="mb-0 flex-fill">Email</h5>
              <i className={`ph-caret-${activeSection === "email" ? "up" : "down"}`}></i>
            </div>
            <div className={`card-body ${activeSection !== null && activeSection !== "email" ? "d-none" : ""}`}>
              <div className="row mb-3">
                <div className="col-md-6">
                  <label className="form-label">Messages per page</label>
                  <select
                    className="form-select"
                    value={settings.messagesPerPage}
                    onChange={(e) => updateSetting("messagesPerPage", e.target.value)}
                  >
                    <option value="25">25</option>
                    <option value="50">50</option>
                    <option value="100">100</option>
                  </select>
                </div>
                <div className="col-md-6">
                  <label className="form-label">Default reply mode</label>
                  <select
                    className="form-select"
                    value={settings.defaultReplyMode}
                    onChange={(e) => updateSetting("defaultReplyMode", e.target.value)}
                  >
                    <option value="reply">Reply</option>
                    <option value="replyAll">Reply All</option>
                  </select>
                </div>
              </div>
              <div className="row mb-3">
                <div className="col-md-6">
                  <label className="form-label">Email signature</label>
                  <textarea
                    className="form-control"
                    rows={3}
                    placeholder="Enter your email signature..."
                    value={settings.emailSignature}
                    onChange={(e) => updateSetting("emailSignature", e.target.value)}
                  ></textarea>
                </div>
                <div className="col-md-6">
                  <label className="form-label">Compose format</label>
                  <select
                    className="form-select mb-3"
                    value={settings.composeFormat}
                    onChange={(e) => updateSetting("composeFormat", e.target.value)}
                  >
                    <option value="html">Rich Text (HTML)</option>
                    <option value="plain">Plain Text</option>
                  </select>
                  <SettingSwitch
                    label="Request read receipts"
                    checked={settings.readReceipts}
                    onChange={(v) => updateSetting("readReceipts", v)}
                  />
                </div>
              </div>
            </div>
          </div>

          {/* Calendar Settings */}
          <div className="card">
            <div
              className="card-header d-flex align-items-center"
              onClick={() => setActiveSection(activeSection === "calendar" ? null : "calendar")}
              style={{ cursor: "pointer" }}
            >
              <i className="ph-calendar me-2 text-purple"></i>
              <h5 className="mb-0 flex-fill">Calendar</h5>
              <i className={`ph-caret-${activeSection === "calendar" ? "up" : "down"}`}></i>
            </div>
            <div className={`card-body ${activeSection !== null && activeSection !== "calendar" ? "d-none" : ""}`}>
              <div className="row mb-3">
                <div className="col-md-6">
                  <label className="form-label">Default view</label>
                  <select
                    className="form-select"
                    value={settings.calendarDefaultView}
                    onChange={(e) => updateSetting("calendarDefaultView", e.target.value)}
                  >
                    <option value="month">Month</option>
                    <option value="week">Week</option>
                    <option value="day">Day</option>
                    <option value="agenda">Agenda</option>
                  </select>
                </div>
                <div className="col-md-6">
                  <label className="form-label">Week starts on</label>
                  <select
                    className="form-select"
                    value={settings.weekStartsOn}
                    onChange={(e) => updateSetting("weekStartsOn", e.target.value)}
                  >
                    <option value="monday">Monday</option>
                    <option value="sunday">Sunday</option>
                    <option value="saturday">Saturday</option>
                  </select>
                </div>
              </div>
              <div className="row mb-3">
                <div className="col-md-6">
                  <label className="form-label">Working hours start</label>
                  <input
                    type="time"
                    className="form-control"
                    value={settings.workingHoursStart}
                    onChange={(e) => updateSetting("workingHoursStart", e.target.value)}
                  />
                </div>
                <div className="col-md-6">
                  <label className="form-label">Working hours end</label>
                  <input
                    type="time"
                    className="form-control"
                    value={settings.workingHoursEnd}
                    onChange={(e) => updateSetting("workingHoursEnd", e.target.value)}
                  />
                </div>
              </div>
              <div className="row">
                <div className="col-md-6">
                  <label className="form-label">Default reminder</label>
                  <select
                    className="form-select"
                    value={settings.defaultReminder}
                    onChange={(e) => updateSetting("defaultReminder", e.target.value)}
                  >
                    <option value="5">5 minutes before</option>
                    <option value="10">10 minutes before</option>
                    <option value="15">15 minutes before</option>
                    <option value="30">30 minutes before</option>
                    <option value="60">1 hour before</option>
                  </select>
                </div>
                <div className="col-md-6">
                  <label className="form-label">Default event duration</label>
                  <select
                    className="form-select"
                    value={settings.defaultEventDuration}
                    onChange={(e) => updateSetting("defaultEventDuration", e.target.value)}
                  >
                    <option value="15">15 minutes</option>
                    <option value="30">30 minutes</option>
                    <option value="60">1 hour</option>
                    <option value="90">1.5 hours</option>
                  </select>
                </div>
              </div>
            </div>
          </div>

          {/* Notifications */}
          <div className="card">
            <div
              className="card-header d-flex align-items-center"
              onClick={() => setActiveSection(activeSection === "notifications" ? null : "notifications")}
              style={{ cursor: "pointer" }}
            >
              <i className="ph-bell me-2 text-warning"></i>
              <h5 className="mb-0 flex-fill">Notifications</h5>
              <i className={`ph-caret-${activeSection === "notifications" ? "up" : "down"}`}></i>
            </div>
            <div className={`card-body ${activeSection !== null && activeSection !== "notifications" ? "d-none" : ""}`}>
              <SettingSwitch
                label="Email notifications"
                description="Receive important updates via email"
                checked={settings.notifyEmail}
                onChange={(v) => updateSetting("notifyEmail", v)}
              />
              <SettingSwitch
                label="Browser notifications"
                description="Show desktop push notifications"
                checked={settings.notifyBrowser}
                onChange={(v) => updateSetting("notifyBrowser", v)}
              />
              <SettingSwitch
                label="Activity notifications"
                description="Get notified about mentions, comments, and shared items"
                checked={settings.notifyActivity}
                onChange={(v) => updateSetting("notifyActivity", v)}
              />
              <SettingSwitch
                label="Security alerts"
                description="Notify about suspicious activity and login attempts"
                checked={settings.notifySecurityAlerts}
                onChange={(v) => updateSetting("notifySecurityAlerts", v)}
              />
              <SettingSwitch
                label="Product updates"
                description="Get notified about new features and improvements"
                checked={settings.notifyProductUpdates}
                onChange={(v) => updateSetting("notifyProductUpdates", v)}
              />
            </div>
          </div>
        </div>

        {/* Right Column */}
        <div className="col-xl-4">
          {/* Account Info */}
          <div className="card">
            <div className="card-header">
              <h5 className="mb-0">
                <i className="ph-user me-2"></i>
                Account
              </h5>
            </div>
            <div className="card-body">
              <div className="list-group list-group-flush">
                <div className="list-group-item d-flex justify-content-between px-0">
                  <span className="text-muted">Name</span>
                  <span className="fw-medium">{displayName}</span>
                </div>
                <div className="list-group-item d-flex justify-content-between px-0">
                  <span className="text-muted">Email</span>
                  <span className="fw-medium">{email}</span>
                </div>
                <div className="list-group-item d-flex justify-content-between px-0">
                  <span className="text-muted">Language</span>
                  <span className="fw-medium">{settings.language.toUpperCase()}</span>
                </div>
                <div className="list-group-item d-flex justify-content-between px-0">
                  <span className="text-muted">Theme</span>
                  <span className="fw-medium text-capitalize">{settings.theme}</span>
                </div>
              </div>
            </div>
            <div className="card-footer">
              <Link href="/profile" className="btn btn-outline-primary btn-sm w-100">
                <i className="ph-user-circle me-2"></i>
                View Full Profile
              </Link>
            </div>
          </div>

          {/* Related Pages */}
          <div className="card">
            <div className="card-header">
              <h5 className="mb-0">
                <i className="ph-link me-2"></i>
                Related
              </h5>
            </div>
            <div className="card-body">
              <div className="d-grid gap-2">
                <Link href="/security" className="btn btn-light text-start">
                  <i className="ph-shield-check me-2 text-danger"></i>
                  Account Security
                </Link>
                <Link href="/privacy" className="btn btn-light text-start">
                  <i className="ph-lock-key me-2 text-success"></i>
                  Privacy Settings
                </Link>
                <Link href="/agent" className="btn btn-light text-start">
                  <i className="ph-robot me-2 text-purple"></i>
                  AI Agent Settings
                </Link>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
