import React, { useEffect, useMemo, useState } from "react";
import { Mail, Phone } from "lucide-react";
import { toast } from "sonner";

import { useAuth } from "../auth/AuthProvider";
import { canEditSupportContactSettings } from "../../lib/accountManagementAccess";
import { Button } from "../ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui/card";
import { Input } from "../ui/input";
import { Label } from "../ui/label";
import {
  createLocationSupport,
  getGlobalLocationSupport,
  updateLocationSupport,
} from "../../services/locationSupportService";

function isValidEmail(email: string) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

export function SupportView() {
  const auth = useAuth();
  const canEdit = useMemo(
    () =>
      canEditSupportContactSettings({
        roleCodes: auth.roleCodes,
        permissionCodes: auth.permissionCodes,
        userName: auth.user?.userName,
      }),
    [auth.roleCodes, auth.permissionCodes, auth.user?.userName],
  );

  const [recordId, setRecordId] = useState<string | null>(null);
  const [supportPhone, setSupportPhone] = useState("");
  const [supportEmail, setSupportEmail] = useState("");
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    let cancelled = false;
    const run = async () => {
      setLoading(true);
      try {
        const dto = await getGlobalLocationSupport();
        if (cancelled) return;
        if (!dto) {
          setRecordId(null);
          setSupportPhone("");
          setSupportEmail("");
          return;
        }
        const id = (dto.id ?? "").trim();
        setRecordId(id || null);
        setSupportPhone((dto.supportPhone ?? "").trim());
        setSupportEmail((dto.supportEmail ?? "").trim());
      } catch (e) {
        if (cancelled) return;
        setRecordId(null);
        setSupportPhone("");
        setSupportEmail("");
        toast.error("Failed to load support settings.", {
          description: e instanceof Error ? e.message : "Please try again.",
        });
      } finally {
        if (!cancelled) setLoading(false);
      }
    };
    void run();
    return () => {
      cancelled = true;
    };
  }, []);

  const onSave = async () => {
    if (!canEdit) {
      toast.error("You do not have permission to update support settings.");
      return;
    }
    const phone = supportPhone.trim();
    const email = supportEmail.trim();
    if (!phone) {
      toast.error("Support phone is required.");
      return;
    }
    if (!email) {
      toast.error("Support email is required.");
      return;
    }
    if (!isValidEmail(email)) {
      toast.error("Support email format is invalid.");
      return;
    }

    setSaving(true);
    try {
      const payload = { supportPhone: phone, supportEmail: email };
      const saved = recordId
        ? await updateLocationSupport(recordId, payload)
        : await createLocationSupport(payload);
      const nextId = (saved.id ?? "").trim();
      setRecordId(nextId || null);
      setSupportPhone((saved.supportPhone ?? "").trim());
      setSupportEmail((saved.supportEmail ?? "").trim());
      toast.success("Support settings saved.");
    } catch (e) {
      toast.error("Failed to save support settings.", {
        description: e instanceof Error ? e.message : "Please try again.",
      });
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="max-w-4xl space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>Support Contact Settings</CardTitle>
          <CardDescription>
            Configure the global support phone and email used by the app support page.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="text-xs text-gray-500">
            {canEdit
              ? recordId
                ? "Existing global support record found. You can update phone and email."
                : "No global support record found. Saving will create a new record."
              : "View only. Only administrators can edit support phone and email."}
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Support Phone *</Label>
              <div className="flex h-10 rounded-md border border-input bg-transparent overflow-hidden">
                <div className="w-10 shrink-0 flex items-center justify-center border-r border-input bg-gray-50">
                  <Phone className="w-4 h-4 text-gray-400" />
                </div>
                <Input
                  className="h-10 border-0 rounded-none shadow-none focus-visible:ring-0 focus-visible:ring-offset-0"
                  value={supportPhone}
                  onChange={(e) => setSupportPhone(e.target.value)}
                  placeholder="e.g. 1-800-SUPPORT"
                  disabled={loading || saving || !canEdit}
                  readOnly={!canEdit}
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label>Support Email *</Label>
              <div className="flex h-10 rounded-md border border-input bg-transparent overflow-hidden">
                <div className="w-10 shrink-0 flex items-center justify-center border-r border-input bg-gray-50">
                  <Mail className="w-4 h-4 text-gray-400" />
                </div>
                <Input
                  className="h-10 border-0 rounded-none shadow-none focus-visible:ring-0 focus-visible:ring-offset-0"
                  value={supportEmail}
                  onChange={(e) => setSupportEmail(e.target.value)}
                  placeholder="support@medvantage.com"
                  disabled={loading || saving || !canEdit}
                  readOnly={!canEdit}
                />
              </div>
            </div>
          </div>

          {canEdit ? (
            <div className="flex justify-end pt-2">
              <Button
                onClick={() => void onSave()}
                className="bg-blue-600 text-white hover:bg-blue-700"
                disabled={loading || saving}
              >
                {saving ? "Saving..." : recordId ? "Update" : "Create"}
              </Button>
            </div>
          ) : null}
        </CardContent>
      </Card>
    </div>
  );
}
