"use client";

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

interface Extension {
  id: string;
  extension: string;
  name: string;
  mohClassId: string | null;
}

interface FollowMe {
  id: string;
  isEnabled: boolean;
  ringTime: number;
  numbers: Array<{
    id: string;
    number: string;
    ringDelay: number;
    orderNum: number;
  }>;
}

interface VoicemailBox {
  id: string;
  mailbox: string;
  email: string | null;
  emailNotify: boolean;
  attachVoicemail: boolean;
  newMessages: number;
}

interface MohClass {
  id: string;
  name: string;
  isDefault: boolean;
}

interface UserVoiceSettingsProps {
  extension?: Extension | null;
  followMe?: FollowMe | null;
  voicemailBox?: VoicemailBox | null;
  mohClasses?: MohClass[];
  tenantId: string;
  userEmail?: string;
}

export default function UserVoiceSettings({
  extension = null,
  followMe = null,
  voicemailBox = null,
  mohClasses = [],
  tenantId,
  userEmail,
}: UserVoiceSettingsProps) {
  const [isPending, startTransition] = useTransition();
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const [activeSection, setActiveSection] = useState<string | null>("forwarding");

  const handleSave = async (section: string, formData: FormData) => {
    startTransition(async () => {
      try {
        const voice = await import("@/app/actions/voice");
        let result;
        if (section === "Call forwarding") {
          result = await voice.updateUserCallForwarding(formData);
        } else if (section === "Music on hold") {
          result = await voice.updateUserMoh(formData);
        } else if (section === "Voicemail") {
          result = await voice.updateUserVoicemail(formData);
        }
        if (result?.error) {
          setMessage({ type: "error", text: result.error });
        } else {
          setMessage({ type: "success", text: result?.message || `${section} settings saved successfully.` });
        }
      } catch {
        setMessage({ type: "error", text: `Failed to save ${section} settings.` });
      }
      setTimeout(() => setMessage(null), 5000);
    });
  };

  const toggleSection = (section: string) => {
    setActiveSection(activeSection === section ? null : section);
  };

  if (!extension) {
    return (
      <>
        <div className="d-flex align-items-center mb-4">
          <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-phone me-2"></i>
              Voice Settings
            </h4>
            <p className="text-muted mb-0 mt-1">Manage your voice and phone settings</p>
          </div>
        </div>

        <div className="alert alert-info">
          <i className="ph-info me-2"></i>
          No phone extension is linked to your account. Please contact your administrator to set up your phone extension.
        </div>
      </>
    );
  }

  return (
    <>
      {/* Page Header */}
      <div className="d-flex align-items-center mb-4">
        <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-phone me-2"></i>
            Voice Settings
          </h4>
          <p className="text-muted mb-0 mt-1">
            Manage your phone settings for extension <strong>{extension.extension}</strong>
          </p>
        </div>
      </div>

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

      <div className="row">
        <div className="col-xl-8">
          {/* Call Forwarding Section */}
          <div className="card mb-3">
            <div
              className="card-header d-flex align-items-center"
              onClick={() => toggleSection("forwarding")}
              style={{ cursor: "pointer" }}
            >
              <i className="ph-phone-forwarded fs-4 me-3 text-primary"></i>
              <div className="flex-fill">
                <h5 className="mb-0">Call Forwarding</h5>
                <small className="text-muted">Forward calls when you&apos;re unavailable</small>
              </div>
              <i className={`ph-caret-${activeSection === "forwarding" ? "up" : "down"} fs-4`}></i>
            </div>
            <div className={`card-body ${activeSection !== "forwarding" ? "d-none" : ""}`}>
              <form
                onSubmit={(e) => {
                  e.preventDefault();
                  const formData = new FormData(e.currentTarget);
                  formData.append("extensionId", extension.id);
                  formData.append("tenantId", tenantId);
                  handleSave("Call forwarding", formData);
                }}
              >
                <div className="mb-3">
                  <div className="form-check form-switch">
                    <input
                      type="checkbox"
                      className="form-check-input"
                      name="forwardingEnabled"
                      defaultChecked={followMe?.isEnabled ?? false}
                    />
                    <label className="form-check-label">Enable Call Forwarding</label>
                  </div>
                  <small className="text-muted">Forward unanswered calls to external numbers</small>
                </div>

                <div className="mb-3">
                  <label className="form-label">Ring Extension First (seconds)</label>
                  <input
                    type="number"
                    className="form-control"
                    name="ringTime"
                    defaultValue={followMe?.ringTime ?? 20}
                    min={5}
                    max={120}
                    style={{ maxWidth: "150px" }}
                  />
                </div>

                <div className="mb-3">
                  <label className="form-label">Forward to Numbers</label>
                  {(followMe?.numbers || []).map((num, idx) => (
                    <div key={num.id} className="input-group mb-2" style={{ maxWidth: "400px" }}>
                      <span className="input-group-text">{idx + 1}</span>
                      <input
                        type="text"
                        className="form-control"
                        name={`forwardNumber_${idx}`}
                        defaultValue={num.number}
                        placeholder="Phone number"
                      />
                    </div>
                  ))}
                  {(!followMe?.numbers || followMe.numbers.length === 0) && (
                    <>
                      <div className="input-group mb-2" style={{ maxWidth: "400px" }}>
                        <span className="input-group-text">1</span>
                        <input type="text" className="form-control" name="forwardNumber_0" placeholder="Phone number" />
                      </div>
                      <div className="input-group mb-2" style={{ maxWidth: "400px" }}>
                        <span className="input-group-text">2</span>
                        <input type="text" className="form-control" name="forwardNumber_1" placeholder="Phone number (optional)" />
                      </div>
                    </>
                  )}
                  <small className="text-muted">Numbers will be tried in order if not answered</small>
                </div>

                <button type="submit" className="btn btn-primary" disabled={isPending}>
                  {isPending ? (
                    <><span className="spinner-border spinner-border-sm me-2"></span>Saving...</>
                  ) : (
                    <><i className="ph-floppy-disk me-2"></i>Save Forwarding Settings</>
                  )}
                </button>
              </form>
            </div>
          </div>

          {/* Music on Hold Section */}
          <div className="card mb-3">
            <div
              className="card-header d-flex align-items-center"
              onClick={() => toggleSection("moh")}
              style={{ cursor: "pointer" }}
            >
              <i className="ph-music-notes fs-4 me-3 text-primary"></i>
              <div className="flex-fill">
                <h5 className="mb-0">Music on Hold</h5>
                <small className="text-muted">Music played when you place callers on hold</small>
              </div>
              <i className={`ph-caret-${activeSection === "moh" ? "up" : "down"} fs-4`}></i>
            </div>
            <div className={`card-body ${activeSection !== "moh" ? "d-none" : ""}`}>
              <form
                onSubmit={(e) => {
                  e.preventDefault();
                  const formData = new FormData(e.currentTarget);
                  formData.append("extensionId", extension.id);
                  formData.append("tenantId", tenantId);
                  handleSave("Music on hold", formData);
                }}
              >
                <div className="mb-3">
                  <label className="form-label">Music on Hold Class</label>
                  <select
                    className="form-select"
                    name="mohClassId"
                    defaultValue={extension.mohClassId || ""}
                    style={{ maxWidth: "300px" }}
                  >
                    <option value="">Use Default</option>
                    {mohClasses.map((moh) => (
                      <option key={moh.id} value={moh.id}>
                        {moh.name} {moh.isDefault && "(Default)"}
                      </option>
                    ))}
                  </select>
                  <small className="text-muted d-block mt-1">
                    Select the music or audio played to callers when you put them on hold
                  </small>
                </div>

                <button type="submit" className="btn btn-primary" disabled={isPending}>
                  {isPending ? (
                    <><span className="spinner-border spinner-border-sm me-2"></span>Saving...</>
                  ) : (
                    <><i className="ph-floppy-disk me-2"></i>Save Music on Hold</>
                  )}
                </button>
              </form>
            </div>
          </div>

          {/* Voicemail Section */}
          <div className="card mb-3">
            <div
              className="card-header d-flex align-items-center"
              onClick={() => toggleSection("voicemail")}
              style={{ cursor: "pointer" }}
            >
              <i className="ph-voicemail fs-4 me-3 text-primary"></i>
              <div className="flex-fill">
                <h5 className="mb-0">Voicemail & Greetings</h5>
                <small className="text-muted">Manage your voicemail settings and greetings</small>
              </div>
              <i className={`ph-caret-${activeSection === "voicemail" ? "up" : "down"} fs-4`}></i>
            </div>
            <div className={`card-body ${activeSection !== "voicemail" ? "d-none" : ""}`}>
              {!voicemailBox ? (
                <div className="alert alert-info mb-0">
                  <i className="ph-info me-2"></i>
                  No voicemail box is configured for your extension. Please contact your administrator.
                </div>
              ) : (
                <form
                  onSubmit={(e) => {
                    e.preventDefault();
                    const formData = new FormData(e.currentTarget);
                    formData.append("voicemailBoxId", voicemailBox.id);
                    formData.append("tenantId", tenantId);
                    handleSave("Voicemail", formData);
                  }}
                >
                  <div className="row">
                    <div className="col-md-6">
                      <div className="mb-3">
                        <label className="form-label">Voicemail Mailbox</label>
                        <input type="text" className="form-control" value={voicemailBox.mailbox} disabled />
                      </div>
                      <div className="mb-3">
                        <label className="form-label">Email for Notifications</label>
                        <input
                          type="email"
                          className="form-control"
                          name="email"
                          defaultValue={voicemailBox.email || ""}
                          placeholder={userEmail}
                        />
                        <small className="text-muted">Receive voicemail notifications at this email</small>
                      </div>
                      <div className="mb-3">
                        <label className="form-label">Change PIN</label>
                        <input
                          type="password"
                          className="form-control"
                          name="pin"
                          placeholder="Enter new PIN"
                          minLength={4}
                          maxLength={8}
                          style={{ maxWidth: "200px" }}
                        />
                        <small className="text-muted">4-8 digits. Leave blank to keep current PIN.</small>
                      </div>
                    </div>
                    <div className="col-md-6">
                      <div className="mb-3">
                        <label className="form-label">Notification Options</label>
                        <div className="form-check mb-2">
                          <input
                            type="checkbox"
                            className="form-check-input"
                            name="emailNotify"
                            defaultChecked={voicemailBox.emailNotify}
                          />
                          <label className="form-check-label">Send email when new voicemail arrives</label>
                        </div>
                        <div className="form-check mb-2">
                          <input
                            type="checkbox"
                            className="form-check-input"
                            name="attachVoicemail"
                            defaultChecked={voicemailBox.attachVoicemail}
                          />
                          <label className="form-check-label">Attach voicemail audio to email</label>
                        </div>
                      </div>
                      <div className="mb-3">
                        <label className="form-label">Messages</label>
                        <div className="alert alert-secondary py-2 mb-0">
                          <i className="ph-envelope me-2"></i>
                          You have <strong>{voicemailBox.newMessages}</strong> new message(s)
                        </div>
                      </div>
                    </div>
                  </div>

                  <button type="submit" className="btn btn-primary" disabled={isPending}>
                    {isPending ? (
                      <><span className="spinner-border spinner-border-sm me-2"></span>Saving...</>
                    ) : (
                      <><i className="ph-floppy-disk me-2"></i>Save Voicemail Settings</>
                    )}
                  </button>
                </form>
              )}
            </div>
          </div>
        </div>

        <div className="col-xl-4">
          {/* Extension Info Card */}
          <div className="card">
            <div className="card-header">
              <h5 className="card-title mb-0">Your Extension</h5>
            </div>
            <div className="card-body">
              <div className="d-flex align-items-center mb-3">
                <span className="avatar avatar-lg bg-primary-lt me-3">
                  <i className="ph-phone fs-1"></i>
                </span>
                <div>
                  <h3 className="mb-0">{extension.extension}</h3>
                  <small className="text-muted">{extension.name}</small>
                </div>
              </div>
              <hr />
              <div className="text-muted">
                <p className="mb-2">
                  <i className="ph-phone me-2"></i>
                  Dial <strong>{extension.extension}</strong> to reach you
                </p>
                {voicemailBox && (
                  <p className="mb-0">
                    <i className="ph-voicemail me-2"></i>
                    Voicemail box: <strong>{voicemailBox.mailbox}</strong>
                  </p>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
