import { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import {
  useTicketDepartments,
  useTicketStatuses,
  useTickets,
} from "../core/_hooks";
import {
  TicketFilters,
  TicketStatus,
  TicketSummary,
} from "../core/_models";
import { PageContainer, PageTitle } from "@/components/ui/Typography";
import { Button } from "@/components/ui/Button";
import { Input } from "@/components/ui/Input";
import { Table } from "@/components/ui/Table";
import { TableColumn } from "@/types";
import { Pagination } from "@/components/ui/Pagination";
import { MessageSquare, Settings, Search, Filter, Eye } from "lucide-react";

const statusColor = (status?: TicketStatus) => {
  if (!status) return "bg-gray-100 text-gray-800";
  if (status.slug === "pending") return "bg-yellow-100 text-yellow-800";
  if (status.slug === "answered") return "bg-green-100 text-green-800";
  if (status.slug === "closed") return "bg-gray-200 text-gray-800";
  return "bg-primary-50 text-primary-700";
};

const TicketsListPage = () => {
  const navigate = useNavigate();
  const [filters, setFilters] = useState<TicketFilters>({
    page: 1,
    limit: 20,
    search: "",
  });
  const { data, isLoading, error } = useTickets(filters);
  const { data: departments } = useTicketDepartments({ activeOnly: true });
  const { data: statuses } = useTicketStatuses({ activeOnly: true });

  const columns: TableColumn[] = useMemo(
    () => [
      {
        key: "ticket_number",
        label: "شماره تیکت",
        align: "right",
        render: (value: string) => value || "-",
      },
      {
        key: "title",
        label: "عنوان",
        align: "right",
        render: (value: string) => value || "-",
      },
      {
        key: "department",
        label: "دپارتمان",
        align: "right",
        render: (_val: unknown, row: TicketSummary) => row.department?.name || "-",
      },
      {
        key: "status",
        label: "وضعیت",
        align: "right",
        render: (_val: unknown, row: TicketSummary) => (
          <span
            className={`px-2 py-1 rounded-full text-xs font-medium ${statusColor(
              row.status
            )}`}
          >
            {row.status?.name || "-"}
          </span>
        ),
      },
      {
        key: "assigned_to",
        label: "مسئول",
        align: "right",
        render: (_val: unknown, row: TicketSummary) =>
          row.assigned_user
            ? `${row.assigned_user.first_name || ""} ${
                row.assigned_user.last_name || ""
              }`.trim() || row.assigned_user.username
            : row.assigned_to || "-",
      },
      {
        key: "updated_at",
        label: "آخرین بروزرسانی",
        align: "right",
        render: (value: string) => value || "-",
      },
      {
        key: "actions",
        label: "عملیات",
        align: "right",
        render: (_val: unknown, row: TicketSummary) => (
          <button
            onClick={() => navigate(`/tickets/${row.id}`)}
            className="text-primary-600 hover:text-primary-800"
          >
            <Eye className="h-4 w-4" />
          </button>
        ),
      },
    ],
    [navigate]
  );

  const handlePageChange = (page: number) => {
    setFilters((prev) => ({ ...prev, page }));
  };

  const handleFilterChange = (
    key: keyof TicketFilters,
    value: string | number | undefined
  ) => {
    setFilters((prev) => ({
      ...prev,
      [key]: value,
      page: 1,
    }));
  };

  if (error) {
    return (
      <PageContainer>
        <div className="card p-6 text-center text-red-600 dark:text-red-400">
          خطا در بارگذاری تیکت‌ها
        </div>
      </PageContainer>
    );
  }

  return (
    <PageContainer>
      <div className="space-y-6">
        {/* Header */}
        <div className="flex flex-col space-y-3 sm:flex-row sm:items-center sm:justify-between sm:space-y-0">
          <div>
            <PageTitle className="flex items-center gap-2">
              <MessageSquare className="h-6 w-6" />
              مدیریت تیکت‌ها
            </PageTitle>
            <p className="text-gray-600 dark:text-gray-400 mt-1">
              {data?.total || 0} تیکت ثبت شده
            </p>
          </div>
          <div className="flex gap-3">
            <Button
              variant="secondary"
              className="flex items-center gap-2"
              onClick={() => navigate("/tickets/config")}
            >
              <Settings className="h-4 w-4" />
              تنظیمات تیکت
            </Button>
          </div>
        </div>

        {/* Filters */}
        <div className="card p-4 sm:p-6">
          {isLoading ? (
            <div className="space-y-4 animate-pulse">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-24 mb-2"></div>
                  <div className="h-10 bg-gray-200 dark:bg-gray-700 rounded-lg"></div>
                </div>
                <div>
                  <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-24 mb-2"></div>
                  <div className="h-10 bg-gray-200 dark:bg-gray-700 rounded-lg"></div>
                </div>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                {[...Array(3)].map((_, i) => (
                  <div key={i}>
                    <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-20 mb-2"></div>
                    <div className="h-10 bg-gray-200 dark:bg-gray-700 rounded-lg"></div>
                  </div>
                ))}
              </div>
            </div>
          ) : (
            <>
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center gap-2">
                  <Filter className="h-5 w-5 text-gray-500" />
                  <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">فیلترها</h3>
                </div>
                <Button
                  variant="secondary"
                  size="sm"
                  onClick={() =>
                    setFilters({
                      page: 1,
                      limit: 20,
                      search: "",
                    })
                  }
                >
                  <Filter className="h-4 w-4 ml-2" />
                  پاک کردن فیلترها
                </Button>
              </div>
              <div className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="relative">
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      جستجو
                    </label>
                    <Search className="absolute right-3 top-10 h-4 w-4 text-gray-400" />
                    <input
                      value={filters.search || ""}
                      onChange={(e) => handleFilterChange("search", e.target.value)}
                      placeholder="جستجو در عنوان یا شماره تیکت"
                      className="w-full pr-9 pl-3 py-3 text-base border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:text-gray-100 transition-all duration-200"
                    />
                  </div>
                  <Input
                    label="شناسه مسئول"
                    type="number"
                    value={filters.assigned_to || ""}
                    onChange={(e) =>
                      handleFilterChange(
                        "assigned_to",
                        e.target.value ? Number(e.target.value) : undefined
                      )
                    }
                  />
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      وضعیت
                    </label>
                    <select
                      value={filters.status_id || ""}
                      onChange={(e) =>
                        handleFilterChange(
                          "status_id",
                          e.target.value ? Number(e.target.value) : undefined
                        )
                      }
                      className="w-full px-3 py-3 text-base border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:text-gray-100 transition-all duration-200"
                    >
                      <option value="">همه وضعیت‌ها</option>
                      {statuses?.map((status) => (
                        <option key={status.id} value={status.id}>
                          {status.name}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      دپارتمان
                    </label>
                    <select
                      value={filters.department_id || ""}
                      onChange={(e) =>
                        handleFilterChange(
                          "department_id",
                          e.target.value ? Number(e.target.value) : undefined
                        )
                      }
                      className="w-full px-3 py-3 text-base border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:text-gray-100 transition-all duration-200"
                    >
                      <option value="">همه دپارتمان‌ها</option>
                      {departments?.map((department) => (
                        <option key={department.id} value={department.id}>
                          {department.name}
                        </option>
                      ))}
                    </select>
                  </div>
                </div>
              </div>
            </>
          )}
        </div>

        {/* Table */}
        {isLoading ? (
          <Table columns={columns} data={[]} loading />
        ) : !data?.tickets || data.tickets.length === 0 ? (
          <div className="card p-8 text-center text-gray-500 dark:text-gray-400">
            تیکتی برای نمایش وجود ندارد
          </div>
        ) : (
          <>
            <Table columns={columns} data={data.tickets as any[]} />
            {data.total > 0 && (
              <Pagination
                currentPage={filters.page || 1}
                totalPages={Math.max(
                  1,
                  Math.ceil((data.total || 0) / (filters.limit || 20))
                )}
                onPageChange={handlePageChange}
                itemsPerPage={filters.limit || 20}
                totalItems={data.total || 0}
              />
            )}
          </>
        )}
      </div>
    </PageContainer>
  );
};

export default TicketsListPage;


