'use client';

import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Pencil, Trash2 } from 'lucide-react';
import Image from 'next/image';
import Link from 'next/link';
import * as React from 'react';
import { ListingStatusBadge } from '@/components/listings/listing-status-badge';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Select } from '@/components/ui/select';
import { formatPrice } from '@/lib/currency';
import { useListingsSearch } from '@/lib/hooks/use-listings';
import { shimmerBlurDataURL, staticBlurDataURL } from '@/lib/image-blur';
import { listingsApi, type ListingDetail as _ListingDetail } from '@/lib/listings-api';
import { PROPERTY_TYPES, TRANSACTION_TYPES, LISTING_STATUSES } from '@/lib/validations/listings';

function formatDate(dateStr: string | null): string {
  if (!dateStr) return 'N/A';
  return new Date(dateStr).toLocaleDateString('vi-VN', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
  });
}

type ViewMode = 'list' | 'table';

export default function ListingsPage() {
  const [viewMode, setViewMode] = React.useState<ViewMode>('list');
  const [filters, setFilters] = React.useState({
    transactionType: '',
    propertyType: '',
    status: '' as string,
    page: 1,
  });

  const searchParams = React.useMemo(() => {
    const params: Record<string, string | number> = { page: filters.page, limit: 12 };
    if (filters.transactionType) params['transactionType'] = filters.transactionType;
    if (filters.propertyType) params['propertyType'] = filters.propertyType;
    if (filters.status) params['status'] = filters.status;
    return params;
  }, [filters]);

  const { data: result, isLoading: loading } = useListingsSearch(searchParams);

  const queryClient = useQueryClient();
  const deleteMutation = useMutation({
    mutationFn: (id: string) => listingsApi.delete(id),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['listings'] }),
  });

  const handleDelete = (id: string, title: string) => {
    if (!window.confirm(`Xoá tin "${title}"? Thao tác này không thể hoàn tác.`)) return;
    deleteMutation.mutate(id);
  };

  // Stats from current page data
  const stats = React.useMemo(() => {
    if (!result) return { total: 0, active: 0, pending: 0, views: 0 };
    return {
      total: result.total,
      active: result.data.filter((l) => l.status === 'ACTIVE').length,
      pending: result.data.filter((l) => l.status === 'PENDING_REVIEW').length,
      views: result.data.reduce((s, l) => s + l.viewCount, 0),
    };
  }, [result]);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold">Quản lý tin đăng</h1>
          <p className="text-sm text-muted-foreground">
            Quản lý, theo dõi và cập nhật các tin đăng của bạn
          </p>
        </div>
        <Link href="/my-listings/new">
          <Button>Đăng tin mới</Button>
        </Link>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Tổng tin đăng</CardDescription>
            <CardTitle className="text-xl">{loading ? '...' : stats.total}</CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Đang hoạt động</CardDescription>
            <CardTitle className="text-xl text-green-600">
              {loading ? '...' : stats.active}
            </CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Chờ duyệt</CardDescription>
            <CardTitle className="text-xl text-yellow-600">
              {loading ? '...' : stats.pending}
            </CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Tổng lượt xem</CardDescription>
            <CardTitle className="text-xl">{loading ? '...' : stats.views}</CardTitle>
          </CardHeader>
        </Card>
      </div>

      {/* Filters + View Toggle */}
      <div className="flex flex-wrap items-center gap-3">
        <Select
          value={filters.transactionType}
          onChange={(e) =>
            setFilters((f) => ({ ...f, transactionType: e.target.value, page: 1 }))
          }
          className="w-40"
        >
          <option value="">Tất cả giao dịch</option>
          {TRANSACTION_TYPES.map((t) => (
            <option key={t.value} value={t.value}>
              {t.label}
            </option>
          ))}
        </Select>
        <Select
          value={filters.propertyType}
          onChange={(e) =>
            setFilters((f) => ({ ...f, propertyType: e.target.value, page: 1 }))
          }
          className="w-44"
        >
          <option value="">Tất cả loại BĐS</option>
          {PROPERTY_TYPES.map((t) => (
            <option key={t.value} value={t.value}>
              {t.label}
            </option>
          ))}
        </Select>
        <Select
          value={filters.status}
          onChange={(e) => setFilters((f) => ({ ...f, status: e.target.value, page: 1 }))}
          className="w-40"
        >
          <option value="">Tất cả trạng thái</option>
          {Object.entries(LISTING_STATUSES).map(([key, { label }]) => (
            <option key={key} value={key}>
              {label}
            </option>
          ))}
        </Select>

        <div className="ml-auto flex gap-1">
          <Button
            variant={viewMode === 'list' ? 'default' : 'outline'}
            size="sm"
            onClick={() => setViewMode('list')}
          >
            Danh sách
          </Button>
          <Button
            variant={viewMode === 'table' ? 'default' : 'outline'}
            size="sm"
            onClick={() => setViewMode('table')}
          >
            Bảng
          </Button>
        </div>
      </div>

      {/* Error banner */}
      {deleteMutation.isError && (
        <div className="flex items-center justify-between gap-2 rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive">
          <p>Không thể xoá tin. Vui lòng thử lại.</p>
          <button
            type="button"
            onClick={() => deleteMutation.reset()}
            className="text-xs underline"
          >
            Đóng
          </button>
        </div>
      )}

      {/* Content */}
      {loading ? (
        <div className="flex min-h-[300px] items-center justify-center">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
        </div>
      ) : !result || result.data.length === 0 ? (
        <div className="flex min-h-[300px] flex-col items-center justify-center text-muted-foreground">
          <p>Chưa có tin đăng nào</p>
          <Link href="/my-listings/new" className="mt-2">
            <Button variant="outline" size="sm">
              Đăng tin đầu tiên
            </Button>
          </Link>
        </div>
      ) : viewMode === 'list' ? (
        /* List View — each row is a horizontal card (image | content | stats) */
        <ul className="flex flex-col gap-3">
          {result.data.map((listing) => (
            <li key={listing.id}>
              <Card className="overflow-hidden transition-shadow hover:shadow-md">
                <Link href={`/listings/${listing.id}`} className="group block">
                  <div className="flex flex-col sm:flex-row">
                    <div className="relative h-40 w-full shrink-0 bg-muted sm:h-32 sm:w-48">
                      {(listing.property.media?.length ?? 0) > 0 ? (
                        <Image
                          src={listing.property.media![0]?.url ?? ''}
                          alt={listing.property.title}
                          fill
                          sizes="(max-width: 640px) 100vw, 192px"
                          className="object-cover"
                          placeholder="blur"
                          blurDataURL={shimmerBlurDataURL()}
                        />
                      ) : (
                        <div className="flex h-full items-center justify-center text-xs text-muted-foreground">
                          Chưa có ảnh
                        </div>
                      )}
                      <div className="absolute left-2 top-2">
                        <ListingStatusBadge status={listing.status} />
                      </div>
                    </div>
                    <CardContent className="flex flex-1 flex-col gap-2 p-4">
                      <div className="flex flex-wrap items-start justify-between gap-2">
                        <div className="min-w-0 flex-1">
                          <h3 className="line-clamp-1 font-semibold group-hover:text-primary">
                            {listing.property.title}
                          </h3>
                          <p className="mt-0.5 line-clamp-1 text-sm text-muted-foreground">
                            {listing.property.district}, {listing.property.city}
                          </p>
                        </div>
                        <p className="shrink-0 text-lg font-bold text-primary">
                          {formatPrice(listing.priceVND)} VND
                        </p>
                      </div>
                      <div className="flex flex-wrap gap-1.5">
                        <Badge variant="secondary" className="text-xs">
                          {listing.property.areaM2} m²
                        </Badge>
                        {listing.property.bedrooms != null && (
                          <Badge variant="secondary" className="text-xs">
                            {listing.property.bedrooms} PN
                          </Badge>
                        )}
                        {listing.property.bathrooms != null && listing.property.bathrooms > 0 && (
                          <Badge variant="secondary" className="text-xs">
                            {listing.property.bathrooms} PT
                          </Badge>
                        )}
                      </div>
                      <div className="mt-auto flex flex-wrap gap-3 text-xs text-muted-foreground">
                        <span>{listing.viewCount} lượt xem</span>
                        <span>{listing.inquiryCount} liên hệ</span>
                        <span>{listing.saveCount} đã lưu</span>
                      </div>
                    </CardContent>
                  </div>
                </Link>
                <div className="flex justify-end gap-2 border-t px-4 py-2">
                  <Link href={`/my-listings/${listing.id}/edit`}>
                    <Button variant="outline" size="sm">
                      <Pencil className="mr-1 h-3.5 w-3.5" />
                      Sửa
                    </Button>
                  </Link>
                  <Button
                    variant="outline"
                    size="sm"
                    className="text-destructive"
                    disabled={
                      deleteMutation.isPending && deleteMutation.variables === listing.id
                    }
                    onClick={(e) => {
                      e.preventDefault();
                      handleDelete(listing.id, listing.property.title);
                    }}
                  >
                    <Trash2 className="mr-1 h-3.5 w-3.5" />
                    Xoá
                  </Button>
                </div>
              </Card>
            </li>
          ))}
        </ul>
      ) : (
        /* Table View */
        <Card>
          <CardContent className="p-0">
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b text-left">
                    <th className="p-3 font-medium">Tin đăng</th>
                    <th className="p-3 font-medium">Loại</th>
                    <th className="p-3 font-medium text-right">Giá</th>
                    <th className="p-3 font-medium text-right">Diện tích</th>
                    <th className="p-3 font-medium text-center">Trạng thái</th>
                    <th className="p-3 font-medium text-right">Lượt xem</th>
                    <th className="p-3 font-medium text-right">Liên hệ</th>
                    <th className="p-3 font-medium text-right">Ngày đăng</th>
                    <th className="p-3 font-medium text-right">Thao tác</th>
                  </tr>
                </thead>
                <tbody>
                  {result.data.map((listing) => (
                    <tr
                      key={listing.id}
                      className="border-b last:border-0 transition-colors hover:bg-accent/50"
                    >
                      <td className="p-3">
                        <Link
                          href={`/listings/${listing.id}`}
                          className="group flex items-center gap-3"
                        >
                          <div className="relative h-10 w-14 flex-shrink-0 overflow-hidden rounded bg-muted">
                            {listing.property.media.length > 0 ? (
                              <Image
                                src={listing.property.media[0]?.url ?? ''}
                                alt={listing.property.title}
                                fill
                                sizes="56px"
                                className="object-cover"
                                placeholder="blur"
                                blurDataURL={staticBlurDataURL()}
                              />
                            ) : (
                              <div className="flex h-full items-center justify-center text-xs text-muted-foreground">
                                N/A
                              </div>
                            )}
                          </div>
                          <div className="min-w-0">
                            <p className="truncate font-medium group-hover:text-primary">
                              {listing.property.title}
                            </p>
                            <p className="truncate text-xs text-muted-foreground">
                              {listing.property.district}, {listing.property.city}
                            </p>
                          </div>
                        </Link>
                      </td>
                      <td className="p-3 text-xs text-muted-foreground">
                        {listing.property.propertyType}
                      </td>
                      <td className="p-3 text-right font-medium text-primary">
                        {formatPrice(listing.priceVND)}
                      </td>
                      <td className="p-3 text-right">{listing.property.areaM2} m²</td>
                      <td className="p-3 text-center">
                        <ListingStatusBadge status={listing.status} />
                      </td>
                      <td className="p-3 text-right">{listing.viewCount}</td>
                      <td className="p-3 text-right">{listing.inquiryCount}</td>
                      <td className="p-3 text-right text-xs text-muted-foreground">
                        {formatDate(listing.publishedAt ?? listing.createdAt)}
                      </td>
                      <td className="p-3 text-right">
                        <div className="flex justify-end gap-1">
                          <Link href={`/my-listings/${listing.id}/edit`}>
                            <Button variant="ghost" size="sm" aria-label="Sửa tin">
                              <Pencil className="h-3.5 w-3.5" />
                            </Button>
                          </Link>
                          <Button
                            variant="ghost"
                            size="sm"
                            aria-label="Xoá tin"
                            className="text-destructive"
                            disabled={
                              deleteMutation.isPending &&
                              deleteMutation.variables === listing.id
                            }
                            onClick={() => handleDelete(listing.id, listing.property.title)}
                          >
                            <Trash2 className="h-3.5 w-3.5" />
                          </Button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Pagination */}
      {result && result.totalPages > 1 && (
        <div className="flex items-center justify-center gap-2">
          <Button
            variant="outline"
            size="sm"
            disabled={filters.page <= 1}
            onClick={() => setFilters((f) => ({ ...f, page: f.page - 1 }))}
          >
            Trước
          </Button>
          <span className="text-sm text-muted-foreground">
            Trang {result.page} / {result.totalPages}
          </span>
          <Button
            variant="outline"
            size="sm"
            disabled={filters.page >= result.totalPages}
            onClick={() => setFilters((f) => ({ ...f, page: f.page + 1 }))}
          >
            Tiếp
          </Button>
        </div>
      )}
    </div>
  );
}
