'use client';

import { zodResolver } from '@hookform/resolvers/zod';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import Link from 'next/link';
import { useParams, useRouter } from 'next/navigation';
import * as React from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import {
  industrialApi,
  PARK_STATUS_LABELS,
  REGION_LABELS,
  type IndustrialParkStatus,
  type UpdateIndustrialParkPayload,
  type VietnamRegion,
} from '@/lib/khu-cong-nghiep-api';

const STATUS_OPTIONS: IndustrialParkStatus[] = [
  'PLANNING',
  'UNDER_CONSTRUCTION',
  'OPERATIONAL',
  'FULL',
];
const REGION_OPTIONS: VietnamRegion[] = ['NORTH', 'CENTRAL', 'SOUTH'];

const optionalString = z
  .string()
  .optional()
  .transform((v) => (v && v.trim() !== '' ? v.trim() : undefined));

const optionalNonNegativeNumber = z
  .string()
  .optional()
  .refine(
    (v) => v === undefined || v === '' || (!isNaN(Number(v)) && Number(v) >= 0),
    'Phải là số không âm',
  );

const editSchema = z.object({
  name: optionalString,
  nameEn: optionalString,
  slug: optionalString,
  developer: optionalString,
  operator: optionalString,
  status: z.enum(['PLANNING', 'UNDER_CONSTRUCTION', 'OPERATIONAL', 'FULL']),

  address: optionalString,
  district: optionalString,
  province: optionalString,
  region: z.enum(['NORTH', 'CENTRAL', 'SOUTH']),
  latitude: z
    .string()
    .optional()
    .refine(
      (v) => v === undefined || v === '' || (!isNaN(Number(v)) && Number(v) >= -90 && Number(v) <= 90),
      'Vĩ độ từ -90 đến 90',
    ),
  longitude: z
    .string()
    .optional()
    .refine(
      (v) =>
        v === undefined || v === '' || (!isNaN(Number(v)) && Number(v) >= -180 && Number(v) <= 180),
      'Kinh độ từ -180 đến 180',
    ),

  totalAreaHa: optionalNonNegativeNumber,
  leasableAreaHa: optionalNonNegativeNumber,

  landRentUsdM2Year: optionalNonNegativeNumber,
  rbfRentUsdM2Month: optionalNonNegativeNumber,
  rbwRentUsdM2Month: optionalNonNegativeNumber,
  managementFeeUsd: optionalNonNegativeNumber,

  targetIndustries: optionalString,
  infrastructure: optionalString,

  establishedYear: optionalNonNegativeNumber,
  tenantCount: optionalNonNegativeNumber,

  description: optionalString,
  descriptionEn: optionalString,
});

type EditFormValues = z.input<typeof editSchema>;

function infraToText(infra: Record<string, unknown> | null | undefined): string {
  if (!infra) return '';
  return Object.entries(infra)
    .map(([k, v]) => {
      if (v === true) return k;
      return `${k}: ${typeof v === 'string' ? v : JSON.stringify(v)}`;
    })
    .join('\n');
}

function parseInfrastructure(text: string | undefined): Record<string, unknown> | undefined {
  if (!text) return undefined;
  const lines = text.split('\n').map((l) => l.trim()).filter(Boolean);
  if (lines.length === 0) return undefined;
  const out: Record<string, unknown> = {};
  for (const line of lines) {
    const idx = line.indexOf(':');
    if (idx > 0) {
      const key = line.slice(0, idx).trim();
      const value = line.slice(idx + 1).trim();
      if (key) out[key] = value;
    } else {
      out[line] = true;
    }
  }
  return Object.keys(out).length > 0 ? out : undefined;
}

function toNumOrUndef(v: string | undefined): number | undefined {
  if (v === undefined || v === '') return undefined;
  const n = Number(v);
  return isNaN(n) ? undefined : n;
}

export default function EditIndustrialParkPage() {
  const { id } = useParams<{ id: string }>();
  const router = useRouter();
  const queryClient = useQueryClient();
  const [error, setError] = React.useState<string | null>(null);

  const {
    data: park,
    isLoading,
    isError,
  } = useQuery({
    queryKey: ['admin-industrial-park', id],
    queryFn: () => industrialApi.getBySlug(id),
    enabled: Boolean(id),
  });

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<EditFormValues>({
    resolver: zodResolver(editSchema),
    mode: 'onTouched',
    defaultValues: {
      status: 'PLANNING',
      region: 'NORTH',
    },
  });

  React.useEffect(() => {
    if (!park) return;
    reset({
      name: park.name,
      nameEn: park.nameEn ?? '',
      slug: park.slug,
      developer: park.developer,
      operator: park.operator ?? '',
      status: park.status,
      address: park.address,
      district: park.district,
      province: park.province,
      region: park.region,
      latitude: String(park.latitude),
      longitude: String(park.longitude),
      totalAreaHa: String(park.totalAreaHa),
      leasableAreaHa: String(park.leasableAreaHa),
      landRentUsdM2Year: park.landRentUsdM2Year != null ? String(park.landRentUsdM2Year) : '',
      rbfRentUsdM2Month: park.rbfRentUsdM2Month != null ? String(park.rbfRentUsdM2Month) : '',
      rbwRentUsdM2Month: park.rbwRentUsdM2Month != null ? String(park.rbwRentUsdM2Month) : '',
      managementFeeUsd: park.managementFeeUsd != null ? String(park.managementFeeUsd) : '',
      targetIndustries: park.targetIndustries.join(', '),
      infrastructure: infraToText(park.infrastructure),
      establishedYear: park.establishedYear != null ? String(park.establishedYear) : '',
      tenantCount: String(park.tenantCount),
      description: park.description ?? '',
      descriptionEn: park.descriptionEn ?? '',
    });
  }, [park, reset]);

  const updateMutation = useMutation({
    mutationFn: (payload: UpdateIndustrialParkPayload) =>
      industrialApi.updatePark(park?.id ?? id, payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin-industrial-parks'] });
      queryClient.invalidateQueries({ queryKey: ['admin-industrial-park', id] });
      router.push('/industrial-parks');
    },
    onError: (err: unknown) => {
      setError(err instanceof Error ? err.message : 'Có lỗi xảy ra');
    },
  });

  const deleteMutation = useMutation({
    mutationFn: () => industrialApi.deletePark(park?.id ?? id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin-industrial-parks'] });
      router.push('/industrial-parks');
    },
    onError: (err: unknown) => {
      setError(err instanceof Error ? err.message : 'Không thể xoá KCN');
    },
  });

  const onSubmit = (data: EditFormValues) => {
    setError(null);
    const payload: UpdateIndustrialParkPayload = {
      status: data.status,
    };

    if (data.name) payload.name = data.name;
    if (data.nameEn !== undefined) payload.nameEn = data.nameEn;
    if (data.developer) payload.developer = data.developer;
    if (data.operator !== undefined) payload.operator = data.operator;

    const landRent = toNumOrUndef(data.landRentUsdM2Year);
    if (landRent != null) payload.landRentUsdM2Year = landRent;
    const rbfRent = toNumOrUndef(data.rbfRentUsdM2Month);
    if (rbfRent != null) payload.rbfRentUsdM2Month = rbfRent;
    const rbwRent = toNumOrUndef(data.rbwRentUsdM2Month);
    if (rbwRent != null) payload.rbwRentUsdM2Month = rbwRent;
    const mgmtFee = toNumOrUndef(data.managementFeeUsd);
    if (mgmtFee != null) payload.managementFeeUsd = mgmtFee;

    const tenantCount = toNumOrUndef(data.tenantCount);
    if (tenantCount != null) payload.tenantCount = tenantCount;

    if (data.targetIndustries !== undefined) {
      payload.targetIndustries = data.targetIndustries
        ? data.targetIndustries
            .split(',')
            .map((s) => s.trim())
            .filter(Boolean)
        : [];
    }

    const infra = parseInfrastructure(data.infrastructure);
    if (infra) payload.infrastructure = infra;

    if (data.description !== undefined) payload.description = data.description;
    if (data.descriptionEn !== undefined) payload.descriptionEn = data.descriptionEn;

    updateMutation.mutate(payload);
  };

  const handleDelete = () => {
    if (!park) return;
    if (!window.confirm(`Xoá KCN "${park.name}"? Thao tác này không thể hoàn tác.`)) return;
    deleteMutation.mutate();
  };

  if (isLoading) {
    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 (isError || !park) {
    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 KCN</p>
        <Button variant="outline" onClick={() => router.push('/industrial-parks')}>
          Quay lại danh sách
        </Button>
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-4xl space-y-4 sm:space-y-6">
      <div className="flex items-center justify-between gap-3">
        <div>
          <Link
            href="/industrial-parks"
            className="text-sm text-muted-foreground hover:text-foreground"
          >
            ← Danh sách KCN
          </Link>
          <h1 className="mt-1 text-xl font-bold sm:text-2xl">Chỉnh sửa KCN</h1>
        </div>
        <Link href={`/khu-cong-nghiep/${park.slug}`} target="_blank" rel="noreferrer">
          <Button variant="outline">Xem trang công khai</Button>
        </Link>
      </div>

      {error && (
        <div className="rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive">
          {error}
          <button className="ml-2 font-medium underline" onClick={() => setError(null)}>
            Đóng
          </button>
        </div>
      )}

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
        {/* Thông tin cơ bản */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Thông tin cơ bản</CardTitle>
          </CardHeader>
          <CardContent className="grid gap-4 sm:grid-cols-2">
            <div>
              <Label htmlFor="name">Tên KCN</Label>
              <Input id="name" {...register('name')} />
            </div>
            <div>
              <Label htmlFor="nameEn">Tên tiếng Anh</Label>
              <Input id="nameEn" {...register('nameEn')} />
            </div>
            <div>
              <Label htmlFor="slug">Slug</Label>
              <Input id="slug" {...register('slug')} disabled />
            </div>
            <div>
              <Label htmlFor="status">Trạng thái</Label>
              <Select id="status" {...register('status')}>
                {STATUS_OPTIONS.map((s) => (
                  <option key={s} value={s}>
                    {PARK_STATUS_LABELS[s]}
                  </option>
                ))}
              </Select>
            </div>
            <div>
              <Label htmlFor="developer">Chủ đầu tư</Label>
              <Input id="developer" {...register('developer')} />
            </div>
            <div>
              <Label htmlFor="operator">Đơn vị vận hành</Label>
              <Input id="operator" {...register('operator')} />
            </div>
            <div className="sm:col-span-2">
              <Label htmlFor="description">Mô tả</Label>
              <Textarea id="description" rows={3} {...register('description')} />
            </div>
            <div className="sm:col-span-2">
              <Label htmlFor="descriptionEn">Mô tả (Tiếng Anh)</Label>
              <Textarea id="descriptionEn" rows={3} {...register('descriptionEn')} />
            </div>
          </CardContent>
        </Card>

        {/* Vị trí */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Vị trí</CardTitle>
          </CardHeader>
          <CardContent className="grid gap-4 sm:grid-cols-2">
            <div className="sm:col-span-2">
              <Label htmlFor="address">Địa chỉ</Label>
              <Input id="address" {...register('address')} disabled />
            </div>
            <div>
              <Label htmlFor="district">Quận/Huyện</Label>
              <Input id="district" {...register('district')} disabled />
            </div>
            <div>
              <Label htmlFor="province">Tỉnh/Thành phố</Label>
              <Input id="province" {...register('province')} disabled />
            </div>
            <div>
              <Label htmlFor="region">Vùng</Label>
              <Select id="region" {...register('region')} disabled>
                {REGION_OPTIONS.map((r) => (
                  <option key={r} value={r}>
                    {REGION_LABELS[r]}
                  </option>
                ))}
              </Select>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label htmlFor="latitude">Vĩ độ</Label>
                <Input
                  id="latitude"
                  type="number"
                  step="any"
                  {...register('latitude')}
                  disabled
                />
              </div>
              <div>
                <Label htmlFor="longitude">Kinh độ</Label>
                <Input
                  id="longitude"
                  type="number"
                  step="any"
                  {...register('longitude')}
                  disabled
                />
              </div>
            </div>
            <p className="text-xs text-muted-foreground sm:col-span-2">
              Thông tin vị trí được khoá sau khi tạo. Vui lòng tạo KCN mới nếu cần thay đổi.
            </p>
          </CardContent>
        </Card>

        {/* Quy mô & giá thuê */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Quy mô & giá thuê</CardTitle>
          </CardHeader>
          <CardContent className="grid gap-4 sm:grid-cols-2">
            <div>
              <Label htmlFor="totalAreaHa">Tổng diện tích (ha)</Label>
              <Input
                id="totalAreaHa"
                type="number"
                step="any"
                {...register('totalAreaHa')}
                disabled
              />
            </div>
            <div>
              <Label htmlFor="leasableAreaHa">Diện tích cho thuê (ha)</Label>
              <Input
                id="leasableAreaHa"
                type="number"
                step="any"
                {...register('leasableAreaHa')}
                disabled
              />
            </div>
            <div>
              <Label htmlFor="landRentUsdM2Year">Giá thuê đất (USD/m²/năm)</Label>
              <Input
                id="landRentUsdM2Year"
                type="number"
                step="any"
                {...register('landRentUsdM2Year')}
              />
              {errors.landRentUsdM2Year && (
                <p className="mt-1 text-xs text-destructive">
                  {errors.landRentUsdM2Year.message}
                </p>
              )}
            </div>
            <div>
              <Label htmlFor="rbfRentUsdM2Month">Giá thuê nhà xưởng (USD/m²/tháng)</Label>
              <Input
                id="rbfRentUsdM2Month"
                type="number"
                step="any"
                {...register('rbfRentUsdM2Month')}
              />
            </div>
            <div>
              <Label htmlFor="rbwRentUsdM2Month">Giá thuê kho (USD/m²/tháng)</Label>
              <Input
                id="rbwRentUsdM2Month"
                type="number"
                step="any"
                {...register('rbwRentUsdM2Month')}
              />
            </div>
            <div>
              <Label htmlFor="managementFeeUsd">Phí quản lý (USD)</Label>
              <Input
                id="managementFeeUsd"
                type="number"
                step="any"
                {...register('managementFeeUsd')}
              />
            </div>
            <div>
              <Label htmlFor="establishedYear">Năm thành lập</Label>
              <Input
                id="establishedYear"
                type="number"
                {...register('establishedYear')}
                disabled
              />
            </div>
            <div>
              <Label htmlFor="tenantCount">Số khách thuê</Label>
              <Input id="tenantCount" type="number" {...register('tenantCount')} />
            </div>
          </CardContent>
        </Card>

        {/* Tiện ích & ngành nghề */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Tiện ích & ngành nghề</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label htmlFor="targetIndustries">Ngành nghề mục tiêu</Label>
              <Textarea
                id="targetIndustries"
                rows={2}
                placeholder="Phân tách bằng dấu phẩy"
                {...register('targetIndustries')}
              />
            </div>
            <div>
              <Label htmlFor="infrastructure">Hạ tầng & tiện ích</Label>
              <Textarea
                id="infrastructure"
                rows={4}
                placeholder={'Mỗi dòng một mục, dạng "key: value"'}
                {...register('infrastructure')}
              />
            </div>
          </CardContent>
        </Card>

        <div className="flex justify-end gap-3">
          <Link href="/industrial-parks">
            <Button type="button" variant="outline">
              Huỷ
            </Button>
          </Link>
          <Button type="submit" disabled={updateMutation.isPending}>
            {updateMutation.isPending ? 'Đang lưu...' : 'Lưu thay đổi'}
          </Button>
        </div>
      </form>

      {/* Danger zone */}
      <Card className="border-destructive/50">
        <CardHeader>
          <CardTitle className="text-lg text-destructive">Vùng nguy hiểm</CardTitle>
        </CardHeader>
        <CardContent className="flex items-center justify-between gap-3">
          <p className="text-sm text-muted-foreground">
            Xoá KCN sẽ gỡ khỏi danh sách công khai và không thể hoàn tác.
          </p>
          <Button
            type="button"
            variant="destructive"
            onClick={handleDelete}
            disabled={deleteMutation.isPending}
          >
            {deleteMutation.isPending ? 'Đang xoá...' : 'Xoá KCN'}
          </Button>
        </CardContent>
      </Card>
    </div>
  );
}
