"use client";

import { useState, useCallback, useEffect } from "react";
import dynamic from "next/dynamic";
import {
  Wrench,
  Plus,
  X,
  AlertTriangle,
  Clock,
  CheckCircle,
  Filter,
  Inbox,
  Building2,
  Upload,
} from "lucide-react";
import { fetchWithCSRF } from "@/lib/csrf-client";
import type { Lang } from "@/lib/config";

const RealEstateBulkImportModal = dynamic(
  () => import("./real-estate/RealEstateBulkImportModal"),
  { ssr: false },
);

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

type IssueCategory =
  | "plumbing"
  | "electrical"
  | "hvac"
  | "structural"
  | "appliance"
  | "pest_control"
  | "cleaning"
  | "other";

type IssuePriority = "low" | "medium" | "high" | "urgent";

type IssueStatus = "open" | "in_progress" | "resolved" | "closed";

interface PropertySummary {
  id: string;
  titleEn: string;
  titleAr?: string;
  referenceNumber?: string;
  city?: string;
  district?: string;
}

interface TenantIssue {
  id: string;
  title: string;
  description: string;
  category: IssueCategory;
  priority: IssuePriority;
  status: IssueStatus;
  propertyId: string;
  unit: string;
  tenantName: string;
  createdAt: string;
  updatedAt: string;
  property?: PropertySummary | null;
}

// ---------------------------------------------------------------------------
// Constants / labels
// ---------------------------------------------------------------------------

const CATEGORY_LABELS: Record<IssueCategory, { en: string; ar: string }> = {
  plumbing: { en: "Plumbing", ar: "السباكة" },
  electrical: { en: "Electrical", ar: "الكهرباء" },
  hvac: { en: "HVAC", ar: "التكييف" },
  structural: { en: "Structural", ar: "الهيكل" },
  appliance: { en: "Appliance", ar: "الأجهزة" },
  pest_control: { en: "Pest Control", ar: "مكافحة الآفات" },
  cleaning: { en: "Cleaning", ar: "التنظيف" },
  other: { en: "Other", ar: "أخرى" },
};

const PRIORITY_CONFIG: Record<
  IssuePriority,
  { en: string; ar: string; color: string }
> = {
  low: { en: "Low", ar: "منخفض", color: "bg-slate-100 text-slate-700" },
  medium: { en: "Medium", ar: "متوسط", color: "bg-blue-100 text-blue-700" },
  high: { en: "High", ar: "مرتفع", color: "bg-orange-100 text-orange-700" },
  urgent: { en: "Urgent", ar: "عاجل", color: "bg-red-100 text-red-700" },
};

const STATUS_CONFIG: Record<
  IssueStatus,
  { en: string; ar: string; color: string; icon: typeof Clock }
> = {
  open: {
    en: "Open",
    ar: "مفتوح",
    color: "bg-yellow-100 text-yellow-700",
    icon: AlertTriangle,
  },
  in_progress: {
    en: "In Progress",
    ar: "قيد التنفيذ",
    color: "bg-blue-100 text-blue-700",
    icon: Clock,
  },
  resolved: {
    en: "Resolved",
    ar: "تم الحل",
    color: "bg-green-100 text-green-700",
    icon: CheckCircle,
  },
  closed: {
    en: "Closed",
    ar: "مغلق",
    color: "bg-slate-100 text-slate-600",
    icon: CheckCircle,
  },
};

const ALL_CATEGORIES: IssueCategory[] = [
  "plumbing",
  "electrical",
  "hvac",
  "structural",
  "appliance",
  "pest_control",
  "cleaning",
  "other",
];

const ALL_PRIORITIES: IssuePriority[] = ["low", "medium", "high", "urgent"];
const ALL_STATUSES: IssueStatus[] = [
  "open",
  "in_progress",
  "resolved",
  "closed",
];

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function timeAgo(dateStr: string | number, isAr: boolean): string {
  const ts = typeof dateStr === "number" ? dateStr : new Date(dateStr).getTime();
  const seconds = Math.floor((Date.now() - ts) / 1000);
  if (seconds < 60)
    return isAr ? "الآن" : "just now";
  const minutes = Math.floor(seconds / 60);
  if (minutes < 60)
    return isAr ? `منذ ${minutes} دقيقة` : `${minutes}m ago`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24)
    return isAr ? `منذ ${hours} ساعة` : `${hours}h ago`;
  const days = Math.floor(hours / 24);
  return isAr ? `منذ ${days} يوم` : `${days}d ago`;
}

function propertyLabel(
  prop: PropertySummary | null | undefined,
  isAr: boolean,
): string {
  if (!prop) return "";
  const title = isAr && prop.titleAr ? prop.titleAr : prop.titleEn;
  const ref = prop.referenceNumber ? ` (${prop.referenceNumber})` : "";
  return `${title}${ref}`;
}

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

interface TenantIssuesPanelProps {
  lang: string;
}

export default function TenantIssuesPanel({ lang }: TenantIssuesPanelProps) {
  const isAr = lang === "ar";

  // Data state
  const [issues, setIssues] = useState<TenantIssue[]>([]);
  const [properties, setProperties] = useState<PropertySummary[]>([]);
  const [loading, setLoading] = useState(true);

  // Filters
  const [statusFilter, setStatusFilter] = useState<IssueStatus | "all">("all");
  const [priorityFilter, setPriorityFilter] = useState<
    IssuePriority | "all"
  >("all");

  // Create modal
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showImportModal, setShowImportModal] = useState(false);
  const [creating, setCreating] = useState(false);
  const [formData, setFormData] = useState({
    title: "",
    description: "",
    category: "other" as IssueCategory,
    priority: "medium" as IssuePriority,
    propertyId: "",
    unit: "",
    tenantName: "",
  });

  // -------------------------------------------------------------------------
  // Fetch properties (for dropdown)
  // -------------------------------------------------------------------------

  const fetchProperties = useCallback(async () => {
    try {
      const res = await fetchWithCSRF("/api/real-estate/properties");
      if (res.ok) {
        const data = await res.json();
        const list = Array.isArray(data)
          ? data
          : data.properties ?? data.data ?? [];
        setProperties(
          list.map((p: Record<string, unknown>) => ({
            id: (p._id ?? p.id) as string,
            titleEn: (p.titleEn ?? p.title ?? "") as string,
            titleAr: p.titleAr as string | undefined,
            referenceNumber: p.referenceNumber as string | undefined,
            city: p.city as string | undefined,
            district: p.district as string | undefined,
          })),
        );
      }
    } catch {
      // Properties API unavailable
    }
  }, []);

  // -------------------------------------------------------------------------
  // Fetch issues
  // -------------------------------------------------------------------------

  const fetchIssues = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetchWithCSRF("/api/dashboard/tenant-issues");
      if (res.ok) {
        const data = await res.json();
        const list = Array.isArray(data)
          ? data
          : data.issues ?? [];
        setIssues(
          list.map((i: Record<string, unknown>) => ({
            ...i,
            id: (i._id ?? i.id) as string,
            createdAt: i.createdAt as string,
            updatedAt: i.updatedAt as string,
          })) as TenantIssue[],
        );
      }
    } catch {
      // API not available
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchProperties();
    fetchIssues();
  }, [fetchProperties, fetchIssues]);

  // -------------------------------------------------------------------------
  // Create issue
  // -------------------------------------------------------------------------

  const handleCreate = useCallback(async () => {
    if (!formData.title.trim() || !formData.propertyId) return;
    setCreating(true);

    const newIssue: TenantIssue = {
      id: `local-${Date.now()}`,
      ...formData,
      status: "open",
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      property: properties.find((p) => p.id === formData.propertyId) ?? null,
    };

    try {
      const res = await fetchWithCSRF("/api/dashboard/tenant-issues", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      });
      if (res.ok) {
        const saved = await res.json();
        const mapped: TenantIssue = {
          ...saved,
          id: saved._id ?? saved.id,
          createdAt: saved.createdAt,
          updatedAt: saved.updatedAt,
        };
        setIssues((prev) => [mapped, ...prev]);
      } else {
        setIssues((prev) => [newIssue, ...prev]);
      }
    } catch {
      setIssues((prev) => [newIssue, ...prev]);
    } finally {
      setCreating(false);
      setShowCreateModal(false);
      setFormData({
        title: "",
        description: "",
        category: "other",
        priority: "medium",
        propertyId: "",
        unit: "",
        tenantName: "",
      });
    }
  }, [formData, properties]);

  // -------------------------------------------------------------------------
  // Filtered issues
  // -------------------------------------------------------------------------

  const filteredIssues = issues.filter((issue) => {
    if (statusFilter !== "all" && issue.status !== statusFilter) return false;
    if (priorityFilter !== "all" && issue.priority !== priorityFilter)
      return false;
    return true;
  });

  // -------------------------------------------------------------------------
  // Render
  // -------------------------------------------------------------------------

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-orange-100 flex items-center justify-center">
            <Wrench className="w-5 h-5 text-orange-600" />
          </div>
          <div>
            <h2 className="text-xl font-bold text-slate-900">
              {isAr ? "مشاكل المستأجرين" : "Tenant Issues"}
            </h2>
            <p className="text-sm text-slate-500">
              {isAr
                ? "تتبع طلبات الصيانة والإصلاح"
                : "Track maintenance & repair requests"}
            </p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => setShowImportModal(true)}
            className="inline-flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-3 py-2.5 text-sm font-medium text-slate-700 hover:bg-slate-50 transition-colors"
          >
            <Upload className="w-4 h-4" />
            {isAr ? "استيراد CSV" : "Import CSV"}
          </button>
          <button
            onClick={() => setShowCreateModal(true)}
            className="inline-flex items-center gap-2 rounded-xl bg-slate-900 px-4 py-2.5 text-sm font-medium text-white hover:bg-slate-800 transition-colors"
          >
            <Plus className="w-4 h-4" />
            {isAr ? "مشكلة جديدة" : "New Issue"}
          </button>
        </div>
      </div>

      {/* Filter Bar */}
      <div className="flex flex-wrap items-center gap-3">
        <div className="flex items-center gap-1.5 text-sm text-slate-500">
          <Filter className="w-4 h-4" />
          {isAr ? "تصفية:" : "Filter:"}
        </div>

        {/* Status filter */}
        <div className="flex gap-1 flex-wrap">
          <button
            onClick={() => setStatusFilter("all")}
            className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
              statusFilter === "all"
                ? "bg-slate-900 text-white"
                : "bg-white text-slate-600 border border-gray-200 hover:bg-slate-50"
            }`}
          >
            {isAr ? "الكل" : "All"}
          </button>
          {ALL_STATUSES.map((s) => (
            <button
              key={s}
              onClick={() => setStatusFilter(s)}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
                statusFilter === s
                  ? "bg-slate-900 text-white"
                  : "bg-white text-slate-600 border border-gray-200 hover:bg-slate-50"
              }`}
            >
              {isAr ? STATUS_CONFIG[s].ar : STATUS_CONFIG[s].en}
            </button>
          ))}
        </div>

        {/* Priority filter */}
        <select
          value={priorityFilter}
          onChange={(e) =>
            setPriorityFilter(e.target.value as IssuePriority | "all")
          }
          className="rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-xs font-medium text-slate-600 focus:outline-none focus:ring-2 focus:ring-slate-900/10"
        >
          <option value="all">
            {isAr ? "كل الأولويات" : "All Priorities"}
          </option>
          {ALL_PRIORITIES.map((p) => (
            <option key={p} value={p}>
              {isAr ? PRIORITY_CONFIG[p].ar : PRIORITY_CONFIG[p].en}
            </option>
          ))}
        </select>
      </div>

      {/* Issue List */}
      {loading ? (
        <div className="space-y-4">
          {[1, 2, 3].map((i) => (
            <div
              key={i}
              className="animate-pulse rounded-xl bg-white border border-gray-100 p-5"
            >
              <div className="h-4 w-1/3 rounded bg-slate-200" />
              <div className="mt-3 h-3 w-2/3 rounded bg-slate-100" />
              <div className="mt-4 flex gap-2">
                <div className="h-6 w-16 rounded-full bg-slate-100" />
                <div className="h-6 w-16 rounded-full bg-slate-100" />
              </div>
            </div>
          ))}
        </div>
      ) : filteredIssues.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-16 text-center">
          <div className="w-14 h-14 rounded-2xl bg-slate-100 flex items-center justify-center mb-4">
            <Inbox className="w-7 h-7 text-slate-400" />
          </div>
          <h3 className="text-lg font-semibold text-slate-700">
            {isAr ? "لا توجد مشاكل" : "No issues found"}
          </h3>
          <p className="mt-1 text-sm text-slate-500 max-w-sm">
            {isAr
              ? 'لم يتم تسجيل أي طلبات صيانة بعد. انقر على "مشكلة جديدة" للبدء.'
              : 'No maintenance requests logged yet. Click "New Issue" to get started.'}
          </p>
        </div>
      ) : (
        <div className="space-y-3">
          {filteredIssues.map((issue) => {
            const StatusIcon = STATUS_CONFIG[issue.status].icon;
            return (
              <div
                key={issue.id}
                className="rounded-xl bg-white border border-gray-100 shadow-sm p-5 hover:shadow-md transition-shadow"
              >
                <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3">
                  <div className="flex-1 min-w-0">
                    <h3 className="font-semibold text-slate-900 truncate">
                      {issue.title}
                    </h3>
                    {issue.description && (
                      <p className="mt-1 text-sm text-slate-500 line-clamp-2">
                        {issue.description}
                      </p>
                    )}
                    {/* Property badge */}
                    {issue.property && (
                      <div className="mt-2 flex items-center gap-1.5 text-xs text-slate-600">
                        <Building2 className="w-3.5 h-3.5 text-slate-400" />
                        <span className="font-medium">
                          {propertyLabel(issue.property, isAr)}
                        </span>
                      </div>
                    )}
                    <div className="mt-3 flex flex-wrap items-center gap-2">
                      {/* Category badge */}
                      <span className="inline-flex items-center rounded-full bg-slate-100 px-2.5 py-0.5 text-xs font-medium text-slate-700">
                        {isAr
                          ? CATEGORY_LABELS[issue.category].ar
                          : CATEGORY_LABELS[issue.category].en}
                      </span>
                      {/* Priority badge */}
                      <span
                        className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${PRIORITY_CONFIG[issue.priority].color}`}
                      >
                        {isAr
                          ? PRIORITY_CONFIG[issue.priority].ar
                          : PRIORITY_CONFIG[issue.priority].en}
                      </span>
                      {/* Status badge */}
                      <span
                        className={`inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium ${STATUS_CONFIG[issue.status].color}`}
                      >
                        <StatusIcon className="w-3 h-3" />
                        {isAr
                          ? STATUS_CONFIG[issue.status].ar
                          : STATUS_CONFIG[issue.status].en}
                      </span>
                    </div>
                  </div>
                  <div className="flex flex-col items-end gap-1 text-xs text-slate-400 shrink-0">
                    {issue.unit && (
                      <span className="font-medium text-slate-600">
                        {isAr ? "الوحدة:" : "Unit:"} {issue.unit}
                      </span>
                    )}
                    {issue.tenantName && (
                      <span>
                        {isAr ? "المستأجر:" : "Tenant:"} {issue.tenantName}
                      </span>
                    )}
                    <span>{timeAgo(issue.createdAt, isAr)}</span>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Create Issue Modal */}
      {/* Bulk Import Modal */}
      <RealEstateBulkImportModal
        lang={lang as Lang}
        isOpen={showImportModal}
        onClose={() => setShowImportModal(false)}
        onImportComplete={() => {
          fetchIssues();
          setShowImportModal(false);
        }}
        initialEntityType="tenant_issues"
      />

      {/* Create Issue Modal */}
      {showCreateModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4">
          <div
            className="w-full max-w-lg rounded-2xl bg-white shadow-xl"
            dir={isAr ? "rtl" : "ltr"}
          >
            {/* Modal header */}
            <div className="flex items-center justify-between border-b border-gray-100 px-6 py-4">
              <h3 className="text-lg font-bold text-slate-900">
                {isAr ? "مشكلة جديدة" : "New Issue"}
              </h3>
              <button
                onClick={() => setShowCreateModal(false)}
                className="rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600 transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Modal body */}
            <div className="space-y-4 px-6 py-5">
              {/* Property selector */}
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  {isAr ? "العقار" : "Property"} *
                </label>
                {properties.length > 0 ? (
                  <select
                    value={formData.propertyId}
                    onChange={(e) =>
                      setFormData((d) => ({ ...d, propertyId: e.target.value }))
                    }
                    className="w-full rounded-xl border border-gray-200 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-slate-900/10"
                  >
                    <option value="">
                      {isAr ? "اختر العقار..." : "Select property..."}
                    </option>
                    {properties.map((p) => (
                      <option key={p.id} value={p.id}>
                        {propertyLabel(p, isAr)}
                        {p.city ? ` - ${p.city}` : ""}
                      </option>
                    ))}
                  </select>
                ) : (
                  <p className="text-sm text-slate-400 italic">
                    {isAr
                      ? "لا توجد عقارات. أضف عقارًا أولاً."
                      : "No properties found. Add a property first."}
                  </p>
                )}
              </div>

              {/* Title */}
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  {isAr ? "العنوان" : "Title"} *
                </label>
                <input
                  type="text"
                  value={formData.title}
                  onChange={(e) =>
                    setFormData((d) => ({ ...d, title: e.target.value }))
                  }
                  placeholder={
                    isAr ? "مثل: تسرب مياه في الحمام" : "e.g. Bathroom leak"
                  }
                  className="w-full rounded-xl border border-gray-200 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-slate-900/10"
                />
              </div>

              {/* Description */}
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  {isAr ? "الوصف" : "Description"}
                </label>
                <textarea
                  value={formData.description}
                  onChange={(e) =>
                    setFormData((d) => ({ ...d, description: e.target.value }))
                  }
                  rows={3}
                  placeholder={
                    isAr
                      ? "وصف تفصيلي للمشكلة..."
                      : "Detailed description of the issue..."
                  }
                  className="w-full rounded-xl border border-gray-200 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-slate-900/10 resize-none"
                />
              </div>

              {/* Category + Priority row */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">
                    {isAr ? "الفئة" : "Category"}
                  </label>
                  <select
                    value={formData.category}
                    onChange={(e) =>
                      setFormData((d) => ({
                        ...d,
                        category: e.target.value as IssueCategory,
                      }))
                    }
                    className="w-full rounded-xl border border-gray-200 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-slate-900/10"
                  >
                    {ALL_CATEGORIES.map((c) => (
                      <option key={c} value={c}>
                        {isAr
                          ? CATEGORY_LABELS[c].ar
                          : CATEGORY_LABELS[c].en}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">
                    {isAr ? "الأولوية" : "Priority"}
                  </label>
                  <select
                    value={formData.priority}
                    onChange={(e) =>
                      setFormData((d) => ({
                        ...d,
                        priority: e.target.value as IssuePriority,
                      }))
                    }
                    className="w-full rounded-xl border border-gray-200 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-slate-900/10"
                  >
                    {ALL_PRIORITIES.map((p) => (
                      <option key={p} value={p}>
                        {isAr
                          ? PRIORITY_CONFIG[p].ar
                          : PRIORITY_CONFIG[p].en}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              {/* Unit + Tenant Name row */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">
                    {isAr ? "الوحدة" : "Unit"}
                  </label>
                  <input
                    type="text"
                    value={formData.unit}
                    onChange={(e) =>
                      setFormData((d) => ({ ...d, unit: e.target.value }))
                    }
                    placeholder={isAr ? "مثل: شقة 4B" : "e.g. Apt 4B"}
                    className="w-full rounded-xl border border-gray-200 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-slate-900/10"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">
                    {isAr ? "اسم المستأجر" : "Tenant Name"}
                  </label>
                  <input
                    type="text"
                    value={formData.tenantName}
                    onChange={(e) =>
                      setFormData((d) => ({
                        ...d,
                        tenantName: e.target.value,
                      }))
                    }
                    placeholder={isAr ? "اسم المستأجر" : "Tenant name"}
                    className="w-full rounded-xl border border-gray-200 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-slate-900/10"
                  />
                </div>
              </div>
            </div>

            {/* Modal footer */}
            <div className="flex items-center justify-end gap-3 border-t border-gray-100 px-6 py-4">
              <button
                onClick={() => setShowCreateModal(false)}
                className="rounded-xl px-4 py-2.5 text-sm font-medium text-slate-600 hover:bg-slate-100 transition-colors"
              >
                {isAr ? "إلغاء" : "Cancel"}
              </button>
              <button
                onClick={handleCreate}
                disabled={creating || !formData.title.trim() || !formData.propertyId}
                className="inline-flex items-center gap-2 rounded-xl bg-slate-900 px-5 py-2.5 text-sm font-medium text-white hover:bg-slate-800 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {creating
                  ? isAr
                    ? "جارٍ الإنشاء..."
                    : "Creating..."
                  : isAr
                    ? "إنشاء"
                    : "Create Issue"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
