/**
 * Viewing Feedback Modal
 * Post-viewing feedback form for broker observations and client rating
 */

"use client";

import { useState } from "react";
import type { Lang } from "@/lib/config";
import { fetchWithCSRF } from "@/lib/csrf-client";
import {
  X,
  Loader2,
  Star,
  ThumbsUp,
  ThumbsDown,
  MessageSquare,
  Save,
} from "lucide-react";

interface ViewingFeedbackModalProps {
  lang: Lang;
  viewingId: string;
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

const INTEREST_LEVELS = [
  {
    value: "hot",
    labelEn: "Hot",
    labelAr: "مهتم جداً",
    color: "bg-red-100 text-red-700 border-red-200",
  },
  {
    value: "warm",
    labelEn: "Warm",
    labelAr: "مهتم",
    color: "bg-amber-100 text-amber-700 border-amber-200",
  },
  {
    value: "cool",
    labelEn: "Cool",
    labelAr: "متردد",
    color: "bg-blue-100 text-blue-700 border-blue-200",
  },
  {
    value: "cold",
    labelEn: "Cold",
    labelAr: "غير مهتم",
    color: "bg-slate-100 text-slate-600 border-slate-200",
  },
];

const PRICE_OPTIONS = [
  { value: "bargain", labelEn: "Bargain", labelAr: "سعر ممتاز" },
  { value: "fair", labelEn: "Fair", labelAr: "سعر عادل" },
  { value: "too_high", labelEn: "Too High", labelAr: "سعر مرتفع" },
];

const SIZE_OPTIONS = [
  { value: "too_small", labelEn: "Too Small", labelAr: "صغير جداً" },
  { value: "just_right", labelEn: "Just Right", labelAr: "مناسب" },
  { value: "spacious", labelEn: "Spacious", labelAr: "واسع" },
];

const LOCATION_OPTIONS = [
  { value: "convenient", labelEn: "Convenient", labelAr: "موقع ممتاز" },
  { value: "acceptable", labelEn: "Acceptable", labelAr: "مقبول" },
  { value: "too_far", labelEn: "Too Far", labelAr: "بعيد جداً" },
];

const SUGGESTED_ACTIONS = [
  {
    value: "make_offer",
    labelEn: "Ready to Make Offer",
    labelAr: "جاهز لتقديم عرض",
  },
  {
    value: "second_viewing",
    labelEn: "Wants Second Viewing",
    labelAr: "يريد معاينة ثانية",
  },
  {
    value: "show_similar",
    labelEn: "Show Similar Properties",
    labelAr: "عرض عقارات مشابهة",
  },
  { value: "not_interested", labelEn: "Not Interested", labelAr: "غير مهتم" },
];

export default function ViewingFeedbackModal({
  lang,
  viewingId,
  isOpen,
  onClose,
  onSuccess,
}: ViewingFeedbackModalProps) {
  const isAr = lang === "ar";

  const [overallRating, setOverallRating] = useState(0);
  const [interestLevel, setInterestLevel] = useState("");
  const [priceOpinion, setPriceOpinion] = useState("");
  const [sizeOpinion, setSizeOpinion] = useState("");
  const [locationOpinion, setLocationOpinion] = useState("");
  const [conditionNote, setConditionNote] = useState("");
  const [wouldRecommend, setWouldRecommend] = useState<boolean | null>(null);
  const [brokerNotes, setBrokerNotes] = useState("");
  const [suggestedAction, setSuggestedAction] = useState("");
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  if (!isOpen) return null;

  const handleSubmit = async () => {
    setError(null);
    setSaving(true);

    try {
      const res = await fetchWithCSRF(
        `/api/real-estate/viewings/${viewingId}/feedback`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            overallRating: overallRating || undefined,
            interestLevel: interestLevel || undefined,
            priceOpinion: priceOpinion || undefined,
            sizeOpinion: sizeOpinion || undefined,
            locationOpinion: locationOpinion || undefined,
            conditionNote: conditionNote || undefined,
            wouldRecommend,
            brokerNotes: brokerNotes || undefined,
            suggestedAction: suggestedAction || undefined,
          }),
        },
      );

      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || `Failed (${res.status})`);
      }

      onSuccess();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Unknown error");
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
      <div className="relative max-h-[90vh] w-full max-w-lg overflow-y-auto rounded-xl bg-white p-6 shadow-2xl">
        {/* Header */}
        <div className="mb-5 flex items-center justify-between">
          <h2 className="text-lg font-bold text-slate-900">
            {isAr ? "تقييم المعاينة" : "Viewing Feedback"}
          </h2>
          <button
            onClick={onClose}
            className="rounded-lg p-2 text-slate-400 hover:bg-slate-100"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

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

        <div className="space-y-5">
          {/* Overall Rating */}
          <div>
            <label className="mb-2 block text-sm font-medium text-slate-700">
              <Star className="mr-1 inline h-4 w-4" />
              {isAr ? "التقييم العام" : "Overall Rating"}
            </label>
            <div className="flex gap-1">
              {[1, 2, 3, 4, 5].map((n) => (
                <button
                  key={n}
                  type="button"
                  onClick={() => setOverallRating(n)}
                  className="p-1 transition-transform hover:scale-110"
                >
                  <Star
                    className={`h-7 w-7 ${
                      n <= overallRating
                        ? "fill-amber-400 text-amber-400"
                        : "text-slate-300"
                    }`}
                  />
                </button>
              ))}
            </div>
          </div>

          {/* Interest Level */}
          <div>
            <label className="mb-2 block text-sm font-medium text-slate-700">
              {isAr ? "مستوى الاهتمام" : "Interest Level"}
            </label>
            <div className="flex flex-wrap gap-2">
              {INTEREST_LEVELS.map((level) => (
                <button
                  key={level.value}
                  type="button"
                  onClick={() => setInterestLevel(level.value)}
                  className={`rounded-full border px-3 py-1.5 text-xs font-semibold transition ${
                    interestLevel === level.value
                      ? level.color
                      : "border-slate-200 bg-white text-slate-500 hover:bg-slate-50"
                  }`}
                >
                  {isAr ? level.labelAr : level.labelEn}
                </button>
              ))}
            </div>
          </div>

          {/* Opinions Row */}
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
            {/* Price */}
            <div>
              <label className="mb-1.5 block text-xs font-medium text-slate-600">
                {isAr ? "رأي السعر" : "Price Opinion"}
              </label>
              <div className="flex flex-col gap-1">
                {PRICE_OPTIONS.map((opt) => (
                  <button
                    key={opt.value}
                    type="button"
                    onClick={() => setPriceOpinion(opt.value)}
                    className={`rounded-lg px-2 py-1.5 text-xs font-medium text-left transition ${
                      priceOpinion === opt.value
                        ? "bg-brand-green/10 text-brand-green border border-brand-green/30"
                        : "bg-slate-50 text-slate-600 border border-transparent hover:bg-slate-100"
                    }`}
                  >
                    {isAr ? opt.labelAr : opt.labelEn}
                  </button>
                ))}
              </div>
            </div>

            {/* Size */}
            <div>
              <label className="mb-1.5 block text-xs font-medium text-slate-600">
                {isAr ? "رأي المساحة" : "Size Opinion"}
              </label>
              <div className="flex flex-col gap-1">
                {SIZE_OPTIONS.map((opt) => (
                  <button
                    key={opt.value}
                    type="button"
                    onClick={() => setSizeOpinion(opt.value)}
                    className={`rounded-lg px-2 py-1.5 text-xs font-medium text-left transition ${
                      sizeOpinion === opt.value
                        ? "bg-brand-green/10 text-brand-green border border-brand-green/30"
                        : "bg-slate-50 text-slate-600 border border-transparent hover:bg-slate-100"
                    }`}
                  >
                    {isAr ? opt.labelAr : opt.labelEn}
                  </button>
                ))}
              </div>
            </div>

            {/* Location */}
            <div>
              <label className="mb-1.5 block text-xs font-medium text-slate-600">
                {isAr ? "رأي الموقع" : "Location Opinion"}
              </label>
              <div className="flex flex-col gap-1">
                {LOCATION_OPTIONS.map((opt) => (
                  <button
                    key={opt.value}
                    type="button"
                    onClick={() => setLocationOpinion(opt.value)}
                    className={`rounded-lg px-2 py-1.5 text-xs font-medium text-left transition ${
                      locationOpinion === opt.value
                        ? "bg-brand-green/10 text-brand-green border border-brand-green/30"
                        : "bg-slate-50 text-slate-600 border border-transparent hover:bg-slate-100"
                    }`}
                  >
                    {isAr ? opt.labelAr : opt.labelEn}
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* Would Recommend */}
          <div>
            <label className="mb-2 block text-sm font-medium text-slate-700">
              {isAr ? "هل ينصح بالعقار؟" : "Would Recommend?"}
            </label>
            <div className="flex gap-3">
              <button
                type="button"
                onClick={() => setWouldRecommend(true)}
                className={`flex items-center gap-2 rounded-lg border px-4 py-2 text-sm font-medium transition ${
                  wouldRecommend === true
                    ? "border-emerald-300 bg-emerald-50 text-emerald-700"
                    : "border-slate-200 bg-white text-slate-500 hover:bg-slate-50"
                }`}
              >
                <ThumbsUp className="h-4 w-4" />
                {isAr ? "نعم" : "Yes"}
              </button>
              <button
                type="button"
                onClick={() => setWouldRecommend(false)}
                className={`flex items-center gap-2 rounded-lg border px-4 py-2 text-sm font-medium transition ${
                  wouldRecommend === false
                    ? "border-red-300 bg-red-50 text-red-700"
                    : "border-slate-200 bg-white text-slate-500 hover:bg-slate-50"
                }`}
              >
                <ThumbsDown className="h-4 w-4" />
                {isAr ? "لا" : "No"}
              </button>
            </div>
          </div>

          {/* Suggested Action */}
          <div>
            <label className="mb-2 block text-sm font-medium text-slate-700">
              {isAr ? "الإجراء المقترح" : "Suggested Next Action"}
            </label>
            <div className="flex flex-wrap gap-2">
              {SUGGESTED_ACTIONS.map((action) => (
                <button
                  key={action.value}
                  type="button"
                  onClick={() => setSuggestedAction(action.value)}
                  className={`rounded-lg border px-3 py-1.5 text-xs font-medium transition ${
                    suggestedAction === action.value
                      ? "border-blue-300 bg-blue-50 text-blue-700"
                      : "border-slate-200 bg-white text-slate-500 hover:bg-slate-50"
                  }`}
                >
                  {isAr ? action.labelAr : action.labelEn}
                </button>
              ))}
            </div>
          </div>

          {/* Condition Note */}
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">
              {isAr ? "ملاحظة عن حالة العقار" : "Property Condition Note"}
            </label>
            <input
              type="text"
              value={conditionNote}
              onChange={(e) => setConditionNote(e.target.value)}
              placeholder={
                isAr ? "مثال: يحتاج طلاء جديد" : "e.g., Needs fresh paint"
              }
              className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-brand-green focus:outline-none"
            />
          </div>

          {/* Broker Notes */}
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-700">
              <MessageSquare className="mr-1 inline h-4 w-4" />
              {isAr ? "ملاحظات الوسيط" : "Broker Notes"}
            </label>
            <textarea
              value={brokerNotes}
              onChange={(e) => setBrokerNotes(e.target.value)}
              rows={3}
              placeholder={
                isAr
                  ? "ملاحظات إضافية من المعاينة..."
                  : "Additional observations from the viewing..."
              }
              className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-brand-green focus:outline-none"
            />
          </div>
        </div>

        {/* Actions */}
        <div className="mt-6 flex justify-end gap-3">
          <button
            onClick={onClose}
            className="rounded-lg border border-slate-300 px-4 py-2 text-sm text-slate-700 hover:bg-slate-50"
          >
            {isAr ? "إلغاء" : "Cancel"}
          </button>
          <button
            onClick={handleSubmit}
            disabled={saving}
            className="inline-flex items-center gap-2 rounded-lg bg-gradient-to-r from-brand-green to-emerald-600 px-4 py-2 text-sm font-semibold text-white shadow-lg shadow-brand-green/25 hover:shadow-brand-green/40 disabled:opacity-50 transition-all"
          >
            {saving ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <Save className="h-4 w-4" />
            )}
            {isAr ? "حفظ التقييم" : "Save Feedback"}
          </button>
        </div>
      </div>
    </div>
  );
}
