'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 Direction, type ListingDetail, type UpdateListingPayload } from '@/lib/listings-api';
import {
  createListingSchema,
  type CreateListingFormData,
} from '@/lib/validations/listings';

function toNum(v: string | undefined): number | undefined {
  if (!v) return undefined;
  const n = Number(v);
  return Number.isFinite(n) ? n : undefined;
}

function toStrArr(csv: string | undefined): string[] | undefined {
  if (!csv || !csv.trim()) return undefined;
  return csv.split(',').map((s) => s.trim()).filter(Boolean);
}

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 [saving, setSaving] = React.useState(false);
  const [saveMsg, setSaveMsg] = React.useState<{ type: 'success' | 'error'; text: string } | null>(null);

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

  const onSubmit = async (data: CreateListingFormData) => {
    setSaving(true);
    setSaveMsg(null);
    try {
      const payload: UpdateListingPayload = {
        transactionType: data.transactionType,
        propertyType: data.propertyType,
        title: data.title,
        description: data.description,
        address: data.address,
        ward: data.ward,
        district: data.district,
        city: data.city,
        priceVND: data.priceVND,
        areaM2: Number(data.areaM2),
      };
      const lat = toNum(data.latitude);
      if (lat != null) payload.latitude = lat;
      const lng = toNum(data.longitude);
      if (lng != null) payload.longitude = lng;
      const usableAreaM2 = toNum(data.usableAreaM2);
      if (usableAreaM2 != null) payload.usableAreaM2 = usableAreaM2;
      const bedrooms = toNum(data.bedrooms);
      if (bedrooms != null) payload.bedrooms = bedrooms;
      const bathrooms = toNum(data.bathrooms);
      if (bathrooms != null) payload.bathrooms = bathrooms;
      const floors = toNum(data.floors);
      if (floors != null) payload.floors = floors;
      const floor = toNum(data.floor);
      if (floor != null) payload.floor = floor;
      const totalFloors = toNum(data.totalFloors);
      if (totalFloors != null) payload.totalFloors = totalFloors;
      if (data.direction) payload.direction = data.direction as Direction;
      const yearBuilt = toNum(data.yearBuilt);
      if (yearBuilt != null) payload.yearBuilt = yearBuilt;
      if (data.legalStatus) payload.legalStatus = data.legalStatus;
      if (data.projectName) payload.projectName = data.projectName;
      const amenities = toStrArr(data.amenities);
      if (amenities) payload.amenities = amenities;
      if (data.rentPriceMonthly) payload.rentPriceMonthly = data.rentPriceMonthly;
      const commissionPct = toNum(data.commissionPct);
      if (commissionPct != null) payload.commissionPct = commissionPct;
      // Phase B
      if (data.furnishing) payload.furnishing = data.furnishing as UpdateListingPayload['furnishing'];
      if (data.propertyCondition) payload.propertyCondition = data.propertyCondition as UpdateListingPayload['propertyCondition'];
      if (data.balconyDirection) payload.balconyDirection = data.balconyDirection as Direction;
      if (data.maintenanceFeeVND) payload.maintenanceFeeVND = data.maintenanceFeeVND;
      const parkingSlots = toNum(data.parkingSlots);
      if (parkingSlots != null) payload.parkingSlots = parkingSlots;
      const viewType = toStrArr(data.viewType);
      if (viewType) payload.viewType = viewType;
      if (data.petFriendly === 'true') payload.petFriendly = true;
      else if (data.petFriendly === 'false') payload.petFriendly = false;
      const suitableFor = toStrArr(data.suitableFor);
      if (suitableFor) payload.suitableFor = suitableFor;
      if (data.whyThisLocation) payload.whyThisLocation = data.whyThisLocation;

      await listingsApi.update(id, payload);
      setSaveMsg({ type: 'success', text: 'Đã lưu thay đổi.' });
    } catch (err) {
      setSaveMsg({
        type: 'error',
        text: err instanceof Error ? err.message : 'Không thể lưu — vui lòng thử lại.',
      });
    } finally {
      setSaving(false);
    }
  };

  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,
          latitude: property.latitude != null ? String(property.latitude) : '',
          longitude: property.longitude != null ? String(property.longitude) : '',
          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) : '',
          furnishing: property.furnishing ?? '',
          propertyCondition: property.propertyCondition ?? '',
          balconyDirection: property.balconyDirection ?? '',
          maintenanceFeeVND: property.maintenanceFeeVND ?? '',
          parkingSlots: property.parkingSlots != null ? String(property.parkingSlots) : '',
          viewType: property.viewType?.join(', ') ?? '',
          petFriendly:
            property.petFriendly === true
              ? 'true'
              : property.petFriendly === false
                ? 'false'
                : '',
          suitableFor: property.suitableFor?.join(', ') ?? '',
          whyThisLocation: property.whyThisLocation ?? '',
        });
      })
      .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('/my-listings')}>
          Quay lại
        </Button>
      </div>
    );
  }

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

      {saveMsg && (
        <div
          className={
            saveMsg.type === 'success'
              ? 'rounded-md border border-green-500/40 bg-green-500/10 px-3 py-2 text-sm text-green-600 dark:text-green-400'
              : 'rounded-md border border-destructive/50 bg-destructive/10 px-3 py-2 text-sm text-destructive'
          }
        >
          {saveMsg.text}
        </div>
      )}

      <form onSubmit={handleSubmit(onSubmit)}>
        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="grid w-full grid-cols-2 md: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} setValue={setValue} watch={watch} />
              </TabsContent>
              <TabsContent value="details">
                <StepDetails register={register} errors={errors} />
              </TabsContent>
              <TabsContent value="pricing">
                <StepPricing register={register} errors={errors} />
              </TabsContent>
            </CardContent>
          </Card>
        </Tabs>

        <div className="mt-6 flex justify-end gap-3">
          <Button type="button" variant="outline" onClick={() => router.push(`/listings/${id}`)}>
            Huỷ
          </Button>
          <Button type="submit" disabled={saving}>
            {saving ? 'Đang lưu...' : 'Lưu thay đổi'}
          </Button>
        </div>
      </form>
    </div>
  );
}
