"use client";

import { useState } from "react";
import classNames from "classnames";
import type { Lang } from "@/lib/config";

const GOALS = [
  {
    id: "reduce-no-shows",
    labelEn: "Reduce No-Shows",
    labelAr: "تقليل عدم الحضور",
  },
  {
    id: "automate-reminders",
    labelEn: "Automate Appointment Reminders",
    labelAr: "أتمتة تذكيرات المواعيد",
  },
  {
    id: "improve-communication",
    labelEn: "Improve Patient Communication",
    labelAr: "تحسين التواصل مع المرضى",
  },
  {
    id: "manage-locations",
    labelEn: "Manage Multiple Locations",
    labelAr: "إدارة مواقع متعددة",
  },
  {
    id: "online-booking",
    labelEn: "Enable Online Booking",
    labelAr: "تفعيل الحجز عبر الإنترنت",
  },
  {
    id: "staff-scheduling",
    labelEn: "Streamline Staff Scheduling",
    labelAr: "تنظيم جداول الموظفين",
  },
  {
    id: "payment-collection",
    labelEn: "Collect Deposits & Payments",
    labelAr: "تحصيل المقدمات والمدفوعات",
  },
  {
    id: "analytics",
    labelEn: "Track Business Analytics",
    labelAr: "تتبع تحليلات الأعمال",
  },
];

interface OnboardingFormProps {
  lang: Lang;
  isAr: boolean;
  dict: any;
  onSubmit: (data: any) => Promise<void>;
  loading: boolean;
}

export default function OnboardingForm({
  lang,
  isAr,
  dict,
  onSubmit,
  loading,
}: OnboardingFormProps) {
  const [selectedGoals, setSelectedGoals] = useState<string[]>([]);
  const [integrations, setIntegrations] = useState({
    hasCalendar: "",
    calendarSystem: "",
    hasWhatsApp: "",
    teamSize: "",
    otherGoal: "",
  });
  const [errors, setErrors] = useState<Record<string, string>>({});

  const toggleGoal = (goalId: string) => {
    setSelectedGoals((prev) =>
      prev.includes(goalId)
        ? prev.filter((id) => id !== goalId)
        : [...prev, goalId],
    );
  };

  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (selectedGoals.length === 0) {
      newErrors.goals = isAr
        ? "يرجى اختيار هدف واحد على الأقل"
        : "Please select at least one goal";
    }

    if (!integrations.hasCalendar) {
      newErrors.hasCalendar = isAr
        ? "يرجى الإجابة على هذا السؤال"
        : "Please answer this question";
    }

    if (!integrations.hasWhatsApp) {
      newErrors.hasWhatsApp = isAr
        ? "يرجى الإجابة على هذا السؤال"
        : "Please answer this question";
    }

    if (!integrations.teamSize) {
      newErrors.teamSize = isAr
        ? "يرجى اختيار حجم الفريق"
        : "Please select team size";
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm()) {
      return;
    }

    await onSubmit({
      goals: selectedGoals,
      integrations,
    });
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-8" dir={dict.dir}>
      {/* Goals Selection */}
      <div>
        <h3 className="text-lg font-semibold text-brand-ink mb-4">
          {isAr ? "ما هي أهدافك الرئيسية؟" : "What are your primary goals?"}
          <span className="text-red-500 ml-1">*</span>
        </h3>
        <div className="grid md:grid-cols-2 gap-3">
          {GOALS.map((goal) => (
            <label
              key={goal.id}
              className={classNames(
                "flex items-center p-4 rounded-lg border-2 cursor-pointer transition-all",
                selectedGoals.includes(goal.id)
                  ? "border-brand-green bg-brand-green/5"
                  : "border-neutral-200 hover:border-neutral-300",
              )}
            >
              <input
                type="checkbox"
                aria-label={isAr ? goal.labelAr : goal.labelEn}
                checked={selectedGoals.includes(goal.id)}
                onChange={() => toggleGoal(goal.id)}
                className="sr-only"
              />
              <div
                className={classNames(
                  "w-5 h-5 rounded border-2 mr-3 flex items-center justify-center",
                  selectedGoals.includes(goal.id)
                    ? "border-brand-green bg-brand-green"
                    : "border-neutral-300",
                )}
              >
                {selectedGoals.includes(goal.id) && (
                  <svg
                    className="w-3 h-3 text-white"
                    fill="currentColor"
                    viewBox="0 0 20 20"
                  >
                    <path
                      fillRule="evenodd"
                      d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
                      clipRule="evenodd"
                    />
                  </svg>
                )}
              </div>
              <span className="text-sm text-neutral-700">
                {isAr ? goal.labelAr : goal.labelEn}
              </span>
            </label>
          ))}
        </div>
        {errors.goals && (
          <p className="mt-2 text-sm text-red-600">{errors.goals}</p>
        )}

        {/* Other goal */}
        <div className="mt-4">
          <label className="block text-sm font-medium text-neutral-700 mb-1">
            {isAr ? "أهداف أخرى" : "Other goals"}
            <span className="text-neutral-400 text-xs ml-2">
              ({isAr ? "اختياري" : "Optional"})
            </span>
          </label>
          <textarea
            value={integrations.otherGoal}
            onChange={(e) =>
              setIntegrations({ ...integrations, otherGoal: e.target.value })
            }
            rows={2}
            className="w-full rounded-lg border border-neutral-200 px-4 py-2 text-sm focus:border-brand-green focus:outline-none focus:ring-2 focus:ring-brand-green/20"
            placeholder={
              isAr
                ? "أخبرنا عن أي أهداف أخرى..."
                : "Tell us about any other goals..."
            }
          />
        </div>
      </div>

      {/* Integration Questions */}
      <div className="space-y-6">
        <h3 className="text-lg font-semibold text-brand-ink">
          {isAr ? "معلومات التكامل" : "Integration Information"}
        </h3>

        {/* Calendar System */}
        <div>
          <label className="block text-sm font-medium text-neutral-700 mb-2">
            {isAr
              ? "هل لديك نظام تقويم حالي؟"
              : "Do you have an existing calendar system?"}
            <span className="text-red-500 ml-1">*</span>
          </label>
          <div className="space-y-2">
            <label className="flex items-center">
              <input
                type="radio"
                name="hasCalendar"
                value="yes"
                checked={integrations.hasCalendar === "yes"}
                onChange={(e) =>
                  setIntegrations({
                    ...integrations,
                    hasCalendar: e.target.value,
                  })
                }
                className="mr-2"
              />
              <span className="text-sm">{isAr ? "نعم" : "Yes"}</span>
            </label>
            <label className="flex items-center">
              <input
                type="radio"
                name="hasCalendar"
                value="no"
                checked={integrations.hasCalendar === "no"}
                onChange={(e) =>
                  setIntegrations({
                    ...integrations,
                    hasCalendar: e.target.value,
                    calendarSystem: "",
                  })
                }
                className="mr-2"
              />
              <span className="text-sm">{isAr ? "لا" : "No"}</span>
            </label>
          </div>
          {integrations.hasCalendar === "yes" && (
            <input
              type="text"
              aria-label={isAr ? "نظام التقويم" : "Calendar system"}
              value={integrations.calendarSystem}
              onChange={(e) =>
                setIntegrations({
                  ...integrations,
                  calendarSystem: e.target.value,
                })
              }
              placeholder={
                isAr
                  ? "مثال: Google Calendar, Outlook"
                  : "e.g., Google Calendar, Outlook"
              }
              className="mt-2 w-full rounded-lg border border-neutral-200 px-4 py-2 text-sm focus:border-brand-green focus:outline-none focus:ring-2 focus:ring-brand-green/20"
            />
          )}
          {errors.hasCalendar && (
            <p className="mt-1 text-sm text-red-600">{errors.hasCalendar}</p>
          )}
        </div>

        {/* WhatsApp Business */}
        <div>
          <label className="block text-sm font-medium text-neutral-700 mb-2">
            {isAr
              ? "هل لديك WhatsApp Business API؟"
              : "Do you have WhatsApp Business API?"}
            <span className="text-red-500 ml-1">*</span>
          </label>
          <div className="space-y-2">
            <label className="flex items-center">
              <input
                type="radio"
                name="hasWhatsApp"
                value="yes"
                checked={integrations.hasWhatsApp === "yes"}
                onChange={(e) =>
                  setIntegrations({
                    ...integrations,
                    hasWhatsApp: e.target.value,
                  })
                }
                className="mr-2"
              />
              <span className="text-sm">
                {isAr ? "نعم، مُفعّل ويعمل" : "Yes, active and working"}
              </span>
            </label>
            <label className="flex items-center">
              <input
                type="radio"
                name="hasWhatsApp"
                value="planning"
                checked={integrations.hasWhatsApp === "planning"}
                onChange={(e) =>
                  setIntegrations({
                    ...integrations,
                    hasWhatsApp: e.target.value,
                  })
                }
                className="mr-2"
              />
              <span className="text-sm">
                {isAr ? "نخطط للحصول عليه" : "Planning to get it"}
              </span>
            </label>
            <label className="flex items-center">
              <input
                type="radio"
                name="hasWhatsApp"
                value="no"
                checked={integrations.hasWhatsApp === "no"}
                onChange={(e) =>
                  setIntegrations({
                    ...integrations,
                    hasWhatsApp: e.target.value,
                  })
                }
                className="mr-2"
              />
              <span className="text-sm">{isAr ? "لا" : "No"}</span>
            </label>
          </div>
          {errors.hasWhatsApp && (
            <p className="mt-1 text-sm text-red-600">{errors.hasWhatsApp}</p>
          )}
        </div>

        {/* Team Size */}
        <div>
          <label
            htmlFor="teamSize"
            className="block text-sm font-medium text-neutral-700 mb-1"
          >
            {isAr
              ? "كم عدد الأشخاص الذين سيستخدمون النظام؟"
              : "How many people will use the system?"}
            <span className="text-red-500 ml-1">*</span>
          </label>
          <select
            id="teamSize"
            value={integrations.teamSize}
            onChange={(e) =>
              setIntegrations({ ...integrations, teamSize: e.target.value })
            }
            className={classNames(
              "w-full rounded-lg border px-4 py-3 text-sm focus:outline-none focus:ring-2",
              errors.teamSize
                ? "border-red-300 focus:border-red-500 focus:ring-red-200"
                : "border-neutral-200 focus:border-brand-green focus:ring-brand-green/20",
            )}
          >
            <option value="">
              {isAr ? "اختر عدد المستخدمين" : "Select number of users"}
            </option>
            <option value="1-3">{isAr ? "1-3 مستخدمين" : "1-3 users"}</option>
            <option value="4-10">
              {isAr ? "4-10 مستخدمين" : "4-10 users"}
            </option>
            <option value="11-25">
              {isAr ? "11-25 مستخدم" : "11-25 users"}
            </option>
            <option value="26+">{isAr ? "26+ مستخدم" : "26+ users"}</option>
          </select>
          {errors.teamSize && (
            <p className="mt-1 text-sm text-red-600">{errors.teamSize}</p>
          )}
        </div>
      </div>

      {/* Submit Button */}
      <button
        type="submit"
        disabled={loading}
        className="w-full rounded-lg bg-brand-green px-4 py-3 text-sm font-semibold text-white transition-all hover:bg-brand-green/90 focus:outline-none focus:ring-2 focus:ring-brand-green/20 disabled:cursor-not-allowed disabled:opacity-50"
      >
        {loading
          ? isAr
            ? "جاري الإعداد..."
            : "Setting up..."
          : isAr
            ? "إكمال الإعداد"
            : "Complete Setup"}
      </button>
    </form>
  );
}
