'use client';

import { useState, useEffect } from 'react';
import { api, apiPaths } from '@/lib/api';
import { getUser, isLoggedIn } from '@/lib/auth';
import { useI18n } from '@/lib/i18n/context';
import FieldError from '@/app/components/FieldError';
import { parseGuestPhoneForApi } from '@/lib/parseGuestPhone';

const COMPLAINT_TYPE_DEFAULT = 1;
const MAX_COMPLAINT = 500;
const SUCCESS_CLOSE_MS = 3000;

type Props = {
  open: boolean;
  onClose: () => void;
};

export default function ContactModal({ open, onClose }: Props) {
  const { t, isRtl } = useI18n();
  const [loggedIn, setLoggedIn] = useState(false);
  const [userName, setUserName] = useState('');
  const [phoneInput, setPhoneInput] = useState('');
  const [complaint, setComplaint] = useState('');
  const [sending, setSending] = useState(false);
  const [fieldErrors, setFieldErrors] = useState<{
    complaint?: string;
    userName?: string;
    phone?: string;
  }>({});
  const [submitError, setSubmitError] = useState('');
  const [success, setSuccess] = useState(false);

  useEffect(() => {
    if (!open) {
      setSuccess(false);
      setComplaint('');
      setPhoneInput('');
      setFieldErrors({});
      setSubmitError('');
      setSending(false);
      return;
    }
    const li = isLoggedIn();
    setLoggedIn(li);
    if (li) {
      setUserName(getUser()?.name ?? '');
    } else {
      setUserName('');
    }
  }, [open]);

  useEffect(() => {
    if (!success || !open) return;
    const id = window.setTimeout(() => {
      onClose();
    }, SUCCESS_CLOSE_MS);
    return () => window.clearTimeout(id);
  }, [success, open, onClose]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitError('');
    setFieldErrors({});

    if (!complaint.trim()) {
      setFieldErrors({ complaint: t('contact.errorMessage') });
      return;
    }
    if (complaint.trim().length > MAX_COMPLAINT) {
      setFieldErrors({ complaint: t('contact.errorMessageTooLong') });
      return;
    }

    let countryCode = '966';
    let phoneDigits = '';

    if (!loggedIn) {
      if (!userName.trim()) {
        setFieldErrors({ userName: t('contact.errorNameRequired') });
        return;
      }
      const parsed = parseGuestPhoneForApi(phoneInput);
      if (!parsed) {
        setFieldErrors({ phone: t('contact.errorPhoneInvalid') });
        return;
      }
      countryCode = parsed.country_code;
      phoneDigits = parsed.phone;
    }

    setSending(true);
    const body: Record<string, unknown> = {
      complaint: complaint.trim(),
      type: COMPLAINT_TYPE_DEFAULT,
    };

    if (!loggedIn) {
      body.user_name = userName.trim();
      body.country_code = countryCode;
      body.phone = phoneDigits;
    }

    const res = await api.post(apiPaths.general.complaints, body);
    setSending(false);

    if (res.key === 'success') {
      setSuccess(true);
      setComplaint('');
      if (!loggedIn) {
        setUserName('');
        setPhoneInput('');
      }
    } else {
      setSubmitError(res.msg || t('contact.errorSend'));
    }
  };

  if (!open) {
    return null;
  }

  return (
    <div
      dir={isRtl ? 'rtl' : 'ltr'}
      className="fixed inset-0 z-[200] flex items-center justify-center bg-black/50 p-4"
      role="presentation"
      onClick={(e) => {
        if (e.target === e.currentTarget && !success) onClose();
      }}
    >
      <div
        className="relative w-full max-w-md rounded-2xl bg-white p-6 shadow-2xl sm:p-8"
        role="dialog"
        aria-modal="true"
        aria-labelledby="contact-modal-title"
        onClick={(e) => e.stopPropagation()}
      >
        <button
          type="button"
          onClick={onClose}
          className="absolute left-4 top-4 z-10 rounded-lg p-2 text-gray-500 transition-colors hover:bg-gray-100"
          aria-label={t('common.close')}
        >
          <i className="ri-close-line text-xl" aria-hidden />
        </button>

        <h2
          id="contact-modal-title"
          className={`mb-6 pr-10 text-xl font-bold text-[#1e3a5f] sm:text-2xl ${isRtl ? 'text-right' : 'text-left'}`}
        >
          {t('contact.title')}
        </h2>

        {success ? (
          <div className="py-4 text-center">
            <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-emerald-100">
              <i className="ri-check-line text-3xl text-emerald-600" aria-hidden />
            </div>
            <h3 className="mb-2 text-lg font-bold text-gray-900">{t('contact.successTitle')}</h3>
            <p className="text-gray-600">{t('contact.successBody')}</p>
          </div>
        ) : (
          <form onSubmit={(e) => void handleSubmit(e)} className="space-y-5">
            {!loggedIn && (
              <>
                <div>
                  <label htmlFor="contact-modal-name" className="mb-2 block text-sm font-semibold text-gray-800">
                    {t('contact.nameGuest')}
                  </label>
                  <input
                    id="contact-modal-name"
                    type="text"
                    value={userName}
                    onChange={(e) => {
                      setUserName(e.target.value);
                      setFieldErrors((p) => ({ ...p, userName: undefined }));
                    }}
                    autoComplete="name"
                    placeholder={t('contact.namePlaceholder')}
                    className={`w-full rounded-xl border px-4 py-3 text-gray-900 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-[#1e3a5f]/30 ${
                      fieldErrors.userName ? 'border-red-400 ring-1 ring-red-200' : 'border-gray-200'
                    }`}
                    aria-invalid={!!fieldErrors.userName}
                  />
                  <FieldError message={fieldErrors.userName} />
                </div>
                <div>
                  <label htmlFor="contact-modal-phone" className="mb-2 block text-sm font-semibold text-gray-800">
                    {t('contact.phoneGuest')}
                  </label>
                  <input
                    id="contact-modal-phone"
                    type="tel"
                    inputMode="tel"
                    value={phoneInput}
                    onChange={(e) => {
                      setPhoneInput(e.target.value);
                      setFieldErrors((p) => ({ ...p, phone: undefined }));
                    }}
                    dir="ltr"
                    className={`w-full rounded-xl border px-4 py-3 text-gray-900 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-[#1e3a5f]/30 ${
                      fieldErrors.phone ? 'border-red-400 ring-1 ring-red-200' : 'border-gray-200'
                    }`}
                    placeholder={t('contact.phonePlaceholder')}
                    aria-invalid={!!fieldErrors.phone}
                  />
                  <FieldError message={fieldErrors.phone} />
                </div>
              </>
            )}

            <div>
              <label htmlFor="contact-modal-complaint" className="mb-2 block text-sm font-semibold text-gray-800">
                {t('contact.complaintReason')}
              </label>
              <textarea
                id="contact-modal-complaint"
                value={complaint}
                onChange={(e) => {
                  const v = e.target.value.slice(0, MAX_COMPLAINT);
                  setComplaint(v);
                  setFieldErrors((p) => ({ ...p, complaint: undefined }));
                }}
                rows={5}
                maxLength={MAX_COMPLAINT}
                className={`min-h-[120px] w-full resize-none rounded-xl border px-4 py-3 text-gray-900 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-[#1e3a5f]/30 ${
                  fieldErrors.complaint ? 'border-red-400 ring-1 ring-red-200' : 'border-gray-200'
                }`}
                placeholder={t('contact.complaintPlaceholder')}
                aria-invalid={!!fieldErrors.complaint}
              />
              <p className={`mt-1.5 text-xs text-gray-500 ${isRtl ? 'text-left' : 'text-right'}`}>
                {t('contact.charCount', { count: String(complaint.length) })}
              </p>
              <FieldError message={fieldErrors.complaint} />
            </div>

            {submitError && (
              <div className="flex items-center gap-2 rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-800">
                <i className="ri-error-warning-line shrink-0 text-lg" aria-hidden />
                <span>{submitError}</span>
              </div>
            )}

            <button
              type="submit"
              disabled={sending}
              className="w-full rounded-xl bg-[#1e3a5f] py-3.5 font-semibold text-white transition-colors hover:bg-[#1a3254] disabled:opacity-60"
            >
              {sending ? t('contact.sending') : t('contact.submit')}
            </button>
          </form>
        )}
      </div>
    </div>
  );
}
