/**
 * Profile Tab Component
 * Edit user profile information
 */

"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import Image from "next/image";
import type { Lang } from "@/lib/config";

interface ProfileTabProps {
  lang: Lang;
  onUnsavedChanges?: (hasChanges: boolean) => void;
  onClose?: () => void;
}

export default function ProfileTab({
  lang,
  onUnsavedChanges,
  onClose,
}: ProfileTabProps) {
  const isAr = lang === "ar";
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  // Organization role - team members have read-only company fields
  const [isTeamMember, setIsTeamMember] = useState(false);
  const [orgRole, setOrgRole] = useState<string | null>(null);

  // Form state
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    phoneNumber: "",
    companyName: "",
    companySize: "",
    industry: "",
    website: "",
    country: "",
    city: "",
    avatar: "",
  });

  const [originalData, setOriginalData] = useState(formData);
  const [uploadingAvatar, setUploadingAvatar] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const fetchProfile = useCallback(async () => {
    try {
      setLoading(true);
      const response = await fetch("/api/user/profile");
      const data = await response.json();

      if (data.success && data.user) {
        const profile = {
          name: data.user.name || "",
          email: data.user.email || "",
          phoneNumber: data.user.phoneNumber || "",
          companyName: data.user.companyName || "",
          companySize: data.user.companySize || "",
          industry: data.user.industry || "",
          website: data.user.website || "",
          country: data.user.country || "",
          city: data.user.city || "",
          avatar: data.user.avatar || "",
        };
        setFormData(profile);
        setOriginalData(profile);

        // Check if user is a team member (non-owner)
        if (data.organization) {
          setIsTeamMember(data.organization.isTeamMember);
          setOrgRole(data.organization.role);
        }
      }
    } catch (err) {
      console.error("Failed to fetch profile:", err);
      setError(isAr ? "فشل تحميل البيانات" : "Failed to load profile");
    } finally {
      setLoading(false);
    }
  }, [isAr]);

  // Fetch current profile
  useEffect(() => {
    fetchProfile();
  }, [fetchProfile]);

  // Track unsaved changes
  useEffect(() => {
    const hasChanges =
      JSON.stringify(formData) !== JSON.stringify(originalData);
    onUnsavedChanges?.(hasChanges);
  }, [formData, originalData, onUnsavedChanges]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setSuccess(false);
    setSaving(true);

    try {
      // Normalize website URL - add https:// if no protocol provided
      const normalizedData = { ...formData };
      if (
        normalizedData.website &&
        !normalizedData.website.match(/^https?:\/\//i)
      ) {
        normalizedData.website = "https://" + normalizedData.website;
      }

      const { fetchWithCSRF } = await import("@/lib/csrf-client");
      const response = await fetchWithCSRF("/api/user/profile", {
        method: "PUT",
        body: JSON.stringify(normalizedData),
      });

      const data = await response.json();

      if (data.success) {
        setSuccess(true);
        setOriginalData(formData);
        onUnsavedChanges?.(false);
        setTimeout(() => setSuccess(false), 3000);
      } else {
        setError(data.error || (isAr ? "فشل الحفظ" : "Failed to save"));
      }
    } catch (err) {
      console.error("Failed to save profile:", err);
      setError(isAr ? "حدث خطأ أثناء الحفظ" : "An error occurred while saving");
    } finally {
      setSaving(false);
    }
  };

  const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploadingAvatar(true);
    setError(null);

    try {
      const body = new FormData();
      body.append("file", file);

      const { fetchWithCSRF } = await import("@/lib/csrf-client");
      const res = await fetchWithCSRF("/api/user/avatar", {
        method: "POST",
        body,
      });
      const data = await res.json();

      if (data.success && data.avatarUrl) {
        setFormData((prev) => ({ ...prev, avatar: data.avatarUrl }));
        setOriginalData((prev) => ({ ...prev, avatar: data.avatarUrl }));
      } else {
        setError(
          data.error || (isAr ? "فشل رفع الصورة" : "Failed to upload photo"),
        );
      }
    } catch {
      setError(
        isAr ? "حدث خطأ أثناء رفع الصورة" : "An error occurred uploading photo",
      );
    } finally {
      setUploadingAvatar(false);
      if (fileInputRef.current) fileInputRef.current.value = "";
    }
  };

  const handleCancel = () => {
    setFormData(originalData);
    setError(null);
    setSuccess(false);
    onUnsavedChanges?.(false);
    onClose?.();
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-brand-green mx-auto mb-4"></div>
          <p className="text-sm text-slate-600">
            {isAr ? "جاري التحميل..." : "Loading..."}
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-lg font-semibold text-slate-900">
          {isAr ? "معلومات الملف الشخصي" : "Profile Information"}
        </h2>
        <p className="text-sm text-slate-600 mt-1">
          {isAr
            ? "قم بتحديث معلوماتك الشخصية ومعلومات الشركة"
            : "Update your personal and company information"}
        </p>
      </div>

      {error && (
        <div className="rounded-lg bg-red-50 border border-red-200 p-4">
          <p className="text-sm text-red-700">{error}</p>
        </div>
      )}

      {success && (
        <div className="rounded-lg bg-emerald-50 border border-emerald-200 p-4">
          <p className="text-sm text-emerald-700">
            ✓ {isAr ? "تم الحفظ بنجاح" : "Saved successfully"}
          </p>
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Avatar Upload */}
        <div>
          <label className="text-sm font-medium text-slate-700 block mb-2">
            {isAr ? "الصورة الشخصية" : "Profile Picture"}
          </label>
          <div className="flex items-center gap-4">
            {formData.avatar ? (
              <Image
                src={formData.avatar}
                alt={formData.name || "Avatar"}
                width={80}
                height={80}
                className="h-20 w-20 rounded-full object-cover border-2 border-slate-200"
              />
            ) : (
              <div className="h-20 w-20 rounded-full bg-gradient-to-br from-brand-green to-emerald-600 flex items-center justify-center text-2xl font-bold text-white">
                {formData.name.slice(0, 2).toUpperCase() || "??"}
              </div>
            )}
            <input
              ref={fileInputRef}
              type="file"
              accept="image/jpeg,image/png,image/webp,image/gif"
              onChange={handleAvatarUpload}
              className="hidden"
            />
            <button
              type="button"
              onClick={() => fileInputRef.current?.click()}
              disabled={uploadingAvatar}
              className="rounded-lg border-2 border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:border-brand-green hover:bg-slate-50 transition-all disabled:opacity-50"
            >
              {uploadingAvatar
                ? isAr
                  ? "جاري الرفع..."
                  : "Uploading..."
                : isAr
                  ? "تحميل صورة"
                  : "Upload Photo"}
            </button>
          </div>
        </div>

        {/* Personal Information */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="text-sm font-medium text-slate-700 block mb-2">
              {isAr ? "الاسم الكامل" : "Full Name"}{" "}
              <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={formData.name}
              onChange={(e) =>
                setFormData({ ...formData, name: e.target.value })
              }
              required
              dir={isAr ? "rtl" : "ltr"}
              className="w-full rounded-lg border border-slate-300 px-4 py-2.5 text-sm focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 transition-all"
              placeholder={isAr ? "أدخل اسمك الكامل" : "Enter your full name"}
            />
          </div>

          <div>
            <label className="text-sm font-medium text-slate-700 block mb-2">
              {isAr ? "البريد الإلكتروني" : "Email Address"}{" "}
              <span className="text-red-500">*</span>
            </label>
            <div className="relative">
              <input
                type="email"
                value={formData.email}
                onChange={(e) =>
                  setFormData({ ...formData, email: e.target.value })
                }
                required
                dir="ltr"
                disabled
                className="w-full rounded-lg border border-slate-300 px-4 py-2.5 text-sm bg-slate-100 text-slate-600 cursor-not-allowed"
                placeholder={isAr ? "your@email.com" : "your@email.com"}
                title={
                  isAr
                    ? "لا يمكن تغيير عنوان البريد الإلكتروني"
                    : "Email address cannot be changed"
                }
              />
              <p className="text-xs text-slate-500 mt-1">
                {isAr
                  ? "🔒 لا يمكن تغيير عنوان البريد الإلكتروني لأسباب أمنية"
                  : "🔒 Email address cannot be changed for security reasons"}
              </p>
            </div>
          </div>

          <div>
            <label className="text-sm font-medium text-slate-700 block mb-2">
              {isAr ? "رقم الهاتف" : "Phone Number"}
            </label>
            <input
              type="tel"
              value={formData.phoneNumber}
              onChange={(e) =>
                setFormData({ ...formData, phoneNumber: e.target.value })
              }
              dir="ltr"
              className="w-full rounded-lg border border-slate-300 px-4 py-2.5 text-sm focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 transition-all"
              placeholder={
                isAr
                  ? "+974 1234 5678 أو 1234 5678"
                  : "+974 1234 5678 or 1234 5678"
              }
            />
            <p className="text-xs text-slate-500 mt-1">
              {isAr
                ? "📱 يُقبل أي تنسيق - مثال: +974 1234 5678 أو 974-1234-5678 أو 1234 5678"
                : "📱 Any format accepted - e.g., +974 1234 5678, 974-1234-5678, or 1234 5678"}
            </p>
          </div>

          <div>
            <label className="text-sm font-medium text-slate-700 block mb-2">
              {isAr ? "اسم الشركة" : "Company Name"}
              {isTeamMember && (
                <span className="text-xs text-slate-500 ms-2">
                  ({isAr ? "للقراءة فقط" : "read-only"})
                </span>
              )}
            </label>
            <input
              type="text"
              value={formData.companyName}
              onChange={(e) =>
                !isTeamMember &&
                setFormData({ ...formData, companyName: e.target.value })
              }
              dir={isAr ? "rtl" : "ltr"}
              disabled={isTeamMember}
              className={`w-full rounded-lg border border-slate-300 px-4 py-2.5 text-sm transition-all ${
                isTeamMember
                  ? "bg-slate-100 text-slate-600 cursor-not-allowed"
                  : "focus:border-brand-green focus:ring-2 focus:ring-brand-green/20"
              }`}
              placeholder={isAr ? "اسم شركتك" : "Your company name"}
            />
          </div>
        </div>

        {/* Team Member Notice */}
        {isTeamMember && (
          <div className="rounded-lg bg-blue-50 border border-blue-200 p-4">
            <p className="text-sm text-blue-700">
              {isAr
                ? `أنت عضو في الفريق (${orgRole === "ADMIN" ? "مدير" : "موظف"}). معلومات الشركة يتم إدارتها من قبل مالك الحساب.`
                : `You are a team member (${orgRole}). Company information is managed by the account owner.`}
            </p>
          </div>
        )}

        {/* Company Information */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="text-sm font-medium text-slate-700 block mb-2">
              {isAr ? "حجم الشركة" : "Company Size"}
              {isTeamMember && (
                <span className="text-xs text-slate-500 ms-2">
                  ({isAr ? "للقراءة فقط" : "read-only"})
                </span>
              )}
            </label>
            <select
              value={formData.companySize}
              onChange={(e) =>
                !isTeamMember &&
                setFormData({ ...formData, companySize: e.target.value })
              }
              disabled={isTeamMember}
              className={`w-full rounded-lg border border-slate-300 px-4 py-2.5 text-sm transition-all ${
                isTeamMember
                  ? "bg-slate-100 text-slate-600 cursor-not-allowed"
                  : "focus:border-brand-green focus:ring-2 focus:ring-brand-green/20"
              }`}
            >
              <option value="">{isAr ? "اختر الحجم" : "Select size"}</option>
              <option value="1-5">
                {isAr ? "1-5 موظفين" : "1-5 employees"}
              </option>
              <option value="6-20">
                {isAr ? "6-20 موظف" : "6-20 employees"}
              </option>
              <option value="21-50">
                {isAr ? "21-50 موظف" : "21-50 employees"}
              </option>
              <option value="51-200">
                {isAr ? "51-200 موظف" : "51-200 employees"}
              </option>
              <option value="200+">
                {isAr ? "200+ موظف" : "200+ employees"}
              </option>
            </select>
          </div>

          <div>
            <label className="text-sm font-medium text-slate-700 block mb-2">
              {isAr ? "القطاع" : "Industry"}
              {isTeamMember && (
                <span className="text-xs text-slate-500 ms-2">
                  ({isAr ? "للقراءة فقط" : "read-only"})
                </span>
              )}
            </label>
            <select
              value={formData.industry}
              onChange={(e) =>
                !isTeamMember &&
                setFormData({ ...formData, industry: e.target.value })
              }
              disabled={isTeamMember}
              className={`w-full rounded-lg border border-slate-300 px-4 py-2.5 text-sm transition-all ${
                isTeamMember
                  ? "bg-slate-100 text-slate-600 cursor-not-allowed"
                  : "focus:border-brand-green focus:ring-2 focus:ring-brand-green/20"
              }`}
            >
              <option value="">
                {isAr ? "اختر القطاع" : "Select industry"}
              </option>
              <option value="health_care">
                {isAr ? "الصحة والرعاية" : "Health & Care"}
              </option>
              <option value="beauty_wellness">
                {isAr ? "الجمال والعافية" : "Beauty & Wellness"}
              </option>
              <option value="food_hospitality">
                {isAr
                  ? "الطعام والضيافة والإقامة"
                  : "Food, Hospitality & Stays"}
              </option>
              <option value="retail_services">
                {isAr ? "التجزئة والخدمات" : "Retail & Services"}
              </option>
              <option value="property_facilities">
                {isAr ? "العقارات والمرافق" : "Property & Facilities"}
              </option>
              <option value="mobility_automotive">
                {isAr ? "التنقل والسيارات" : "Mobility & Automotive"}
              </option>
              <option value="home_services_trades">
                {isAr ? "خدمات المنازل والحرف" : "Home Services & Trades"}
              </option>
              <option value="education">
                {isAr ? "التعليم" : "Education"}
              </option>
              <option value="events_venues">
                {isAr ? "الفعاليات والقاعات" : "Events & Venues"}
              </option>
              <option value="pet_services">
                {isAr ? "خدمات الحيوانات الأليفة" : "Pet Services"}
              </option>
              <option value="nonprofit_community">
                {isAr ? "المنظمات غير الربحية" : "Nonprofit/Community"}
              </option>
              <option value="public_sector">
                {isAr ? "القطاع العام" : "Public Sector"}
              </option>
              <option value="other">{isAr ? "أخرى" : "Other"}</option>
            </select>
          </div>

          <div>
            <label className="text-sm font-medium text-slate-700 block mb-2">
              {isAr ? "الموقع الإلكتروني" : "Website"}
              {isTeamMember && (
                <span className="text-xs text-slate-500 ms-2">
                  ({isAr ? "للقراءة فقط" : "read-only"})
                </span>
              )}
            </label>
            <div className="relative">
              <input
                type="text"
                value={formData.website}
                onChange={(e) =>
                  !isTeamMember &&
                  setFormData({ ...formData, website: e.target.value })
                }
                dir="ltr"
                disabled={isTeamMember}
                className={`w-full rounded-lg border border-slate-300 px-4 py-2.5 text-sm transition-all ${
                  isTeamMember
                    ? "bg-slate-100 text-slate-600 cursor-not-allowed"
                    : "focus:border-brand-green focus:ring-2 focus:ring-brand-green/20"
                }`}
                placeholder={isAr ? "google.com" : "google.com"}
              />
              {!isTeamMember &&
                formData.website &&
                !formData.website.match(/^https?:\/\//i) && (
                  <span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-slate-400">
                    → https://{formData.website}
                  </span>
                )}
            </div>
            {!isTeamMember && (
              <p className="text-xs text-slate-500 mt-1">
                {isAr
                  ? "✨ أدخل النطاق فقط - سيتم إضافة https:// تلقائياً"
                  : "✨ Enter domain only - https:// will be added automatically"}
              </p>
            )}
          </div>

          <div>
            <label className="text-sm font-medium text-slate-700 block mb-2">
              {isAr ? "الدولة" : "Country"}
              {isTeamMember && (
                <span className="text-xs text-slate-500 ms-2">
                  ({isAr ? "للقراءة فقط" : "read-only"})
                </span>
              )}
            </label>
            <select
              value={formData.country}
              onChange={(e) =>
                !isTeamMember &&
                setFormData({ ...formData, country: e.target.value })
              }
              disabled={isTeamMember}
              className={`w-full rounded-lg border border-slate-300 px-4 py-2.5 text-sm transition-all ${
                isTeamMember
                  ? "bg-slate-100 text-slate-600 cursor-not-allowed"
                  : "focus:border-brand-green focus:ring-2 focus:ring-brand-green/20"
              }`}
            >
              <option value="">
                {isAr ? "اختر الدولة" : "Select country"}
              </option>
              <option value="SA">{isAr ? "السعودية" : "Saudi Arabia"}</option>
              <option value="AE">{isAr ? "الإمارات" : "UAE"}</option>
              <option value="QA">{isAr ? "قطر" : "Qatar"}</option>
              <option value="KW">{isAr ? "الكويت" : "Kuwait"}</option>
              <option value="BH">{isAr ? "البحرين" : "Bahrain"}</option>
              <option value="OM">{isAr ? "عمان" : "Oman"}</option>
            </select>
          </div>
        </div>

        {/* Action Buttons */}
        <div className="flex items-center justify-end gap-3 pt-4 border-t border-slate-200">
          <button
            type="button"
            onClick={handleCancel}
            disabled={saving}
            className="rounded-lg border-2 border-slate-200 px-6 py-2.5 text-sm font-medium text-slate-700 hover:bg-slate-50 transition-all disabled:opacity-50"
          >
            {isAr ? "إلغاء" : "Cancel"}
          </button>
          <button
            type="submit"
            disabled={
              saving ||
              JSON.stringify(formData) === JSON.stringify(originalData)
            }
            className="rounded-lg bg-brand-green px-6 py-2.5 text-sm font-semibold text-white hover:bg-brand-greenHover shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {saving
              ? isAr
                ? "جاري الحفظ..."
                : "Saving..."
              : isAr
                ? "حفظ التغييرات"
                : "Save Changes"}
          </button>
        </div>
      </form>
    </div>
  );
}
