'use client';

import { zodResolver } from '@hookform/resolvers/zod';
import { useParams, useRouter } from 'next/navigation';
import * as React from 'react';
import { useForm } from 'react-hook-form';
import {
  StepBasicInfo,
  StepLocation,
  StepDetails,
  StepPricing,
} from '@/components/listings/listing-form-steps';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import { listingsApi, type ListingDetail } from '@/lib/listings-api';
import {
  createListingSchema,
  type CreateListingFormData,
} from '@/lib/validations/listings';

export default function EditListingPage() {
  const { id } = useParams<{ id: string }>();
  const router = useRouter();
  const [listing, setListing] = React.useState<ListingDetail | null>(null);
  const [loading, setLoading] = React.useState(true);
  const [activeTab, setActiveTab] = React.useState('basic');

  const {
    register,
    reset,
    formState: { errors },
  } = useForm<CreateListingFormData>({
    resolver: zodResolver(createListingSchema),
    mode: 'onTouched',
  });

  React.useEffect(() => {
    listingsApi
      .getById(id)
      .then((data) => {
        setListing(data);
        const { property } = data;
        reset({
          transactionType: data.transactionType,
          propertyType: property.propertyType,
          title: property.title,
          description: property.description,
          address: property.address,
          ward: property.ward,
          district: property.district,
          city: property.city,
          areaM2: String(property.areaM2),
          bedrooms: property.bedrooms != null ? String(property.bedrooms) : '',
          bathrooms: property.bathrooms != null ? String(property.bathrooms) : '',
          floors: property.floors != null ? String(property.floors) : '',
          direction: property.direction ?? '',
          yearBuilt: property.yearBuilt != null ? String(property.yearBuilt) : '',
          legalStatus: property.legalStatus ?? '',
          projectName: property.projectName ?? '',
          amenities: property.amenities?.join(', ') ?? '',
          priceVND: data.priceVND,
          rentPriceMonthly: data.rentPriceMonthly ?? '',
          commissionPct: data.commissionPct != null ? String(data.commissionPct) : '',
        });
      })
      .catch(() => setListing(null))
      .finally(() => setLoading(false));
  }, [id, reset]);

  if (loading) {
    return (
      <div className="flex min-h-[400px] items-center justify-center">
        <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    );
  }

  if (!listing) {
    return (
      <div className="flex min-h-[400px] flex-col items-center justify-center space-y-4">
        <p className="text-destructive">Không tìm thấy tin đăng</p>
        <Button variant="outline" onClick={() => router.push('/listings')}>
          Quay lại
        </Button>
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-3xl space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">Chỉnh sửa tin đăng</h1>
        <Button variant="outline" onClick={() => router.push(`/listings/${id}`)}>
          Xem tin
        </Button>
      </div>

      <p className="text-sm text-muted-foreground">
        Chức năng chỉnh sửa sẽ được hoàn thiện khi backend API hỗ trợ PATCH /listings/:id.
        Hiện tại bạn có thể xem lại thông tin đã nhập.
      </p>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="basic">Cơ bản</TabsTrigger>
          <TabsTrigger value="location">Vị trí</TabsTrigger>
          <TabsTrigger value="details">Chi tiết</TabsTrigger>
          <TabsTrigger value="pricing">Giá cả</TabsTrigger>
        </TabsList>

        <Card className="mt-4">
          <CardContent className="pt-6">
            <TabsContent value="basic">
              <StepBasicInfo register={register} errors={errors} />
            </TabsContent>
            <TabsContent value="location">
              <StepLocation register={register} errors={errors} />
            </TabsContent>
            <TabsContent value="details">
              <StepDetails register={register} errors={errors} />
            </TabsContent>
            <TabsContent value="pricing">
              <StepPricing register={register} errors={errors} />
            </TabsContent>
          </CardContent>
        </Card>
      </Tabs>
    </div>
  );
}
