'use client';

import { useRouter } from 'next/navigation';
import * as React from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import {
  useSavedSearches,
  useDeleteSavedSearch,
  useUpdateSavedSearch,
} from '@/lib/hooks/use-saved-searches';
import { type SavedSearch, type SavedSearchFilters } from '@/lib/saved-search-api';

const PROPERTY_TYPE_LABELS: Record<string, string> = {
  APARTMENT: 'Chung cư',
  HOUSE: 'Nhà phố',
  VILLA: 'Biệt thự',
  LAND: 'Đất nền',
  OFFICE: 'Văn phòng',
  SHOPHOUSE: 'Shophouse',
};

const TRANSACTION_TYPE_LABELS: Record<string, string> = {
  SALE: 'Bán',
  RENT: 'Cho thuê',
};

function formatPrice(value: string): string {
  const num = Number(value);
  if (num >= 1_000_000_000) return `${(num / 1_000_000_000).toFixed(1)} tỷ`;
  if (num >= 1_000_000) return `${(num / 1_000_000).toFixed(0)} triệu`;
  return num.toLocaleString('vi-VN');
}

function formatFilters(filters: SavedSearchFilters): string[] {
  const parts: string[] = [];

  if (filters.transactionType) {
    parts.push(TRANSACTION_TYPE_LABELS[filters.transactionType] ?? filters.transactionType);
  }
  if (filters.propertyType) {
    parts.push(PROPERTY_TYPE_LABELS[filters.propertyType] ?? filters.propertyType);
  }
  if (filters.district) parts.push(filters.district);
  if (filters.city) parts.push(filters.city);
  if (filters.priceMin && filters.priceMax) {
    parts.push(`${formatPrice(filters.priceMin)} - ${formatPrice(filters.priceMax)}`);
  } else if (filters.priceMin) {
    parts.push(`Từ ${formatPrice(filters.priceMin)}`);
  } else if (filters.priceMax) {
    parts.push(`Đến ${formatPrice(filters.priceMax)}`);
  }
  if (filters.areaMin || filters.areaMax) {
    if (filters.areaMin && filters.areaMax) {
      parts.push(`${filters.areaMin} - ${filters.areaMax} m²`);
    } else if (filters.areaMin) {
      parts.push(`Từ ${filters.areaMin} m²`);
    } else if (filters.areaMax) {
      parts.push(`Đến ${filters.areaMax} m²`);
    }
  }
  if (filters.bedrooms) parts.push(`${filters.bedrooms}+ phòng ngủ`);

  return parts;
}

function SavedSearchCard({
  search,
  onDelete,
  onToggleAlert,
  onApplySearch,
}: {
  search: SavedSearch;
  onDelete: (id: string) => void;
  onToggleAlert: (id: string, enabled: boolean) => void;
  onApplySearch: (filters: SavedSearchFilters) => void;
}) {
  const [confirmDelete, setConfirmDelete] = React.useState(false);
  const filterTags = formatFilters(search.filters);

  return (
    <Card className="transition-shadow hover:shadow-md">
      <CardHeader className="pb-3">
        <div className="flex items-start justify-between">
          <div className="min-w-0 flex-1">
            <CardTitle className="truncate text-base">{search.name}</CardTitle>
            <CardDescription className="mt-1 text-xs">
              Tạo lúc {new Date(search.createdAt).toLocaleDateString('vi-VN')}
              {search.lastAlertAt && (
                <> · Thông báo gần nhất: {new Date(search.lastAlertAt).toLocaleDateString('vi-VN')}</>
              )}
            </CardDescription>
          </div>
          <div className="ml-2 flex items-center gap-1">
            <button
              onClick={() => onToggleAlert(search.id, !search.alertEnabled)}
              className={`rounded-full px-2.5 py-0.5 text-xs font-medium transition-colors ${
                search.alertEnabled
                  ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
                  : 'bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400'
              }`}
              title={search.alertEnabled ? 'Tắt thông báo' : 'Bật thông báo'}
            >
              {search.alertEnabled ? 'Thông báo bật' : 'Thông báo tắt'}
            </button>
          </div>
        </div>
      </CardHeader>
      <CardContent>
        {/* Filter tags */}
        {filterTags.length > 0 && (
          <div className="mb-3 flex flex-wrap gap-1.5">
            {filterTags.map((tag, i) => (
              <span
                key={i}
                className="rounded-md bg-accent px-2 py-0.5 text-xs text-accent-foreground"
              >
                {tag}
              </span>
            ))}
          </div>
        )}

        {/* Actions */}
        <div className="flex items-center gap-2">
          <Button
            size="sm"
            variant="default"
            onClick={() => onApplySearch(search.filters)}
          >
            <svg className="mr-1.5 h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
            </svg>
            Tìm kiếm
          </Button>

          {confirmDelete ? (
            <div className="flex items-center gap-1">
              <Button
                size="sm"
                variant="destructive"
                onClick={() => {
                  onDelete(search.id);
                  setConfirmDelete(false);
                }}
              >
                Xác nhận xóa
              </Button>
              <Button
                size="sm"
                variant="ghost"
                onClick={() => setConfirmDelete(false)}
              >
                Hủy
              </Button>
            </div>
          ) : (
            <Button
              size="sm"
              variant="ghost"
              className="text-muted-foreground hover:text-destructive"
              onClick={() => setConfirmDelete(true)}
            >
              <svg className="mr-1 h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
              </svg>
              Xóa
            </Button>
          )}
        </div>
      </CardContent>
    </Card>
  );
}

export default function SavedSearchesPage() {
  const router = useRouter();
  const { data, isLoading, error } = useSavedSearches();
  const deleteMutation = useDeleteSavedSearch();
  const updateMutation = useUpdateSavedSearch();

  const handleDelete = (id: string) => {
    deleteMutation.mutate(id);
  };

  const handleToggleAlert = (id: string, enabled: boolean) => {
    updateMutation.mutate({ id, data: { alertEnabled: enabled } });
  };

  const handleApplySearch = (filters: SavedSearchFilters) => {
    const params = new URLSearchParams();
    Object.entries(filters).forEach(([key, value]) => {
      if (value) params.set(key, String(value));
    });
    const qs = params.toString();
    router.push(`/search${qs ? `?${qs}` : ''}`);
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold md:text-3xl">Tìm kiếm đã lưu</h1>
          <p className="mt-1 text-muted-foreground">
            Quản lý các bộ lọc tìm kiếm và nhận thông báo khi có kết quả mới
          </p>
        </div>
        <Button onClick={() => router.push('/search')}>
          <svg className="mr-1.5 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
          Tìm kiếm mới
        </Button>
      </div>

      {/* Content */}
      {isLoading ? (
        <div className="flex h-64 items-center justify-center">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
        </div>
      ) : error ? (
        <Card>
          <CardContent className="flex h-48 flex-col items-center justify-center gap-3">
            <p className="text-sm text-destructive">Không thể tải danh sách tìm kiếm đã lưu</p>
            <Button variant="outline" size="sm" onClick={() => window.location.reload()}>
              Thử lại
            </Button>
          </CardContent>
        </Card>
      ) : !data || data.data.length === 0 ? (
        <Card>
          <CardContent className="flex h-64 flex-col items-center justify-center gap-4 text-center">
            <div className="rounded-full bg-muted p-4">
              <svg className="h-8 w-8 text-muted-foreground" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
              </svg>
            </div>
            <div>
              <p className="font-medium">Chưa có tìm kiếm nào được lưu</p>
              <p className="mt-1 text-sm text-muted-foreground">
                Bạn có thể lưu bộ lọc tìm kiếm từ trang tìm kiếm để nhận thông báo khi có kết quả mới
              </p>
            </div>
            <Button onClick={() => router.push('/search')}>
              Đi đến trang tìm kiếm
            </Button>
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-4">
          <p className="text-sm text-muted-foreground">
            {data.total} tìm kiếm đã lưu
          </p>
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {data.data.map((search) => (
              <SavedSearchCard
                key={search.id}
                search={search}
                onDelete={handleDelete}
                onToggleAlert={handleToggleAlert}
                onApplySearch={handleApplySearch}
              />
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
