import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { toast } from 'sonner';
import { Plus, Search, Edit, Trash2, MapPin } from 'lucide-react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';

import { deliveryAddressClient } from '../api/deliveryAddressClient';
import { CreateDeliveryAddressDto, UpdateDeliveryAddressDto } from '@d8d/delivery-address-module/schemas';
import { Button } from '@d8d/shared-ui-components/components/ui/button';
import { Input } from '@d8d/shared-ui-components/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@d8d/shared-ui-components/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@d8d/shared-ui-components/components/ui/table';
import { Badge } from '@d8d/shared-ui-components/components/ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@d8d/shared-ui-components/components/ui/dialog';
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@d8d/shared-ui-components/components/ui/form';
import { Switch } from '@d8d/shared-ui-components/components/ui/switch';
import { Skeleton } from '@d8d/shared-ui-components/components/ui/skeleton';
import { DataTablePagination } from '@d8d/shared-ui-components/components/admin/DataTablePagination';
import { UserSelector } from '@d8d/user-management-ui/components';
import { AreaSelect4Level } from '@d8d/area-management-ui/components';
import type { DeliveryAddress, DeliveryAddressQueryParams } from '../types/delivery-address';
import { DeliveryAddressState, DefaultAddressState } from '../types/delivery-address';

// 表单schema
const createFormSchema = CreateDeliveryAddressDto;
const updateFormSchema = UpdateDeliveryAddressDto;

export const DeliveryAddressManagement: React.FC = () => {
  const queryClient = useQueryClient();

  // 状态管理
  const [searchParams, setSearchParams] = useState<DeliveryAddressQueryParams>({
    page: 1,
    limit: 10,
    search: '',
    userId: undefined,
  });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingAddress, setEditingAddress] = useState<DeliveryAddress | null>(null);
  const [isCreateForm, setIsCreateForm] = useState(true);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [addressToDelete, setAddressToDelete] = useState<number | null>(null);

  // 表单实例
  const createForm = useForm({
    resolver: zodResolver(createFormSchema),
    defaultValues: {
      userId: 0,
      name: '',
      phone: '',
      address: '',
      receiverProvince: 0,
      receiverCity: 0,
      receiverDistrict: 0,
      receiverTown: 0,
      isDefault: 0,
    },
  });

  const updateForm = useForm({
    resolver: zodResolver(updateFormSchema),
  });

  // 数据查询
  const { data, isLoading, refetch } = useQuery({
    queryKey: ['delivery-addresses', searchParams],
    queryFn: async () => {
      const res = await deliveryAddressClient.$get({
        query: {
          page: searchParams.page,
          pageSize: searchParams.limit,
          keyword: searchParams.search,
          ...(searchParams.userId && { userId: searchParams.userId }),
        }
      });
      if (res.status !== 200) throw new Error('获取收货地址列表失败');
      return await res.json();
    }
  });

  // 创建地址
  const createMutation = useMutation({
    mutationFn: async (data: any) => {
      const res = await deliveryAddressClient.$post({ json: data });
      if (res.status !== 201) throw new Error('创建失败');
      return await res.json();
    },
    onSuccess: () => {
      toast.success('收货地址创建成功');
      setIsModalOpen(false);
      refetch();
      createForm.reset();
    },
    onError: (error) => {
      toast.error(error.message || '创建失败');
    }
  });

  // 更新地址
  const updateMutation = useMutation({
    mutationFn: async ({ id, data }: { id: number; data: any }) => {
      const res = await deliveryAddressClient[':id']['$put']({
        param: { id },
        json: data,
      });
      if (res.status !== 200) throw new Error('更新失败');
      return await res.json();
    },
    onSuccess: () => {
      toast.success('收货地址更新成功');
      setIsModalOpen(false);
      refetch();
    },
    onError: (error) => {
      toast.error(error.message || '更新失败');
    }
  });

  // 删除地址
  const deleteMutation = useMutation({
    mutationFn: async (id: number) => {
      const res = await deliveryAddressClient[':id']['$delete']({
        param: { id },
      });
      if (res.status !== 204) throw new Error('删除失败');
    },
    onSuccess: () => {
      toast.success('收货地址删除成功');
      setDeleteDialogOpen(false);
      refetch();
    },
    onError: (error) => {
      toast.error(error.message || '删除失败');
    }
  });

  // 业务逻辑函数
  const handleSearch = () => {
    setSearchParams(prev => ({ ...prev, page: 1 }));
  };

  const handleCreateAddress = () => {
    setIsCreateForm(true);
    setEditingAddress(null);
    createForm.reset();
    setIsModalOpen(true);
  };

  const handleEditAddress = (address: DeliveryAddress) => {
    setIsCreateForm(false);
    setEditingAddress(address);

    updateForm.reset({
      name: address.name,
      phone: address.phone,
      address: address.address,
      receiverProvince: address.receiverProvince,
      receiverCity: address.receiverCity,
      receiverDistrict: address.receiverDistrict,
      receiverTown: address.receiverTown,
      isDefault: address.isDefault,
    });

    setIsModalOpen(true);
  };

  const handleDeleteAddress = (id: number) => {
    setAddressToDelete(id);
    setDeleteDialogOpen(true);
  };

  const confirmDelete = () => {
    if (addressToDelete) {
      deleteMutation.mutate(addressToDelete);
    }
  };

  const handleCreateSubmit = (data: any) => {
    createMutation.mutate(data);
  };

  const handleUpdateSubmit = (data: any) => {
    if (editingAddress) {
      updateMutation.mutate({ id: editingAddress.id, data });
    }
  };

  // 状态显示
  const getStatusBadge = (status: DeliveryAddressState) => {
    switch (status) {
      case DeliveryAddressState.ACTIVE:
        return <Badge variant="default" data-testid="status-active">正常</Badge>;
      case DeliveryAddressState.DISABLED:
        return <Badge variant="secondary" data-testid="status-disabled">禁用</Badge>;
      case DeliveryAddressState.DELETED:
        return <Badge variant="destructive" data-testid="status-deleted">删除</Badge>;
      default:
        return <Badge variant="outline" data-testid="status-unknown">未知</Badge>;
    }
  };

  const getIsDefaultBadge = (isDefault: DefaultAddressState) => {
    return isDefault === DefaultAddressState.IS_DEFAULT ? (
      <Badge variant="default" data-testid="is-default-true">默认</Badge>
    ) : (
      <Badge variant="outline" data-testid="is-default-false">非默认</Badge>
    );
  };

  // 格式化地址显示
  const formatAddressDisplay = (address: DeliveryAddress) => {
    const parts = [
      address.province?.name,
      address.city?.name,
      address.district?.name,
      address.town?.name,
      address.address
    ].filter(Boolean);
    return parts.join(' ');
  };

  // 表格加载状态
  const tableContent = isLoading ? (
    <Card>
      <CardHeader>
        <CardTitle>收货地址列表</CardTitle>
        <CardDescription>
          加载中...
        </CardDescription>
      </CardHeader>
      <CardContent>
        <div className="space-y-3">
          {[...Array(5)].map((_, i) => (
            <div key={i} className="flex gap-4">
              <Skeleton className="h-10 flex-1" />
              <Skeleton className="h-10 flex-1" />
              <Skeleton className="h-10 flex-1" />
              <Skeleton className="h-10 w-20" />
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  ) : (
    <Card>
      <CardHeader>
        <CardTitle>收货地址列表</CardTitle>
        <CardDescription>
          共 {data?.data?.total || 0} 条收货地址记录
        </CardDescription>
      </CardHeader>
      <CardContent>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>用户</TableHead>
              <TableHead>收货人</TableHead>
              <TableHead>手机号</TableHead>
              <TableHead>地址</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>默认地址</TableHead>
              <TableHead>创建时间</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {data?.data?.list?.map((address: DeliveryAddress) => (
              <TableRow key={address.id} data-testid={`address-row-${address.id}`}>
                <TableCell data-testid={`address-user-${address.id}`}>
                  <div className="flex items-center gap-2">
                    <MapPin className="h-4 w-4 text-muted-foreground" />
                    <span>{address.user?.name || '未知用户'}</span>
                  </div>
                </TableCell>
                <TableCell data-testid={`address-name-${address.id}`}>{address.name}</TableCell>
                <TableCell data-testid={`address-phone-${address.id}`}>{address.phone}</TableCell>
                <TableCell>
                  <div className="max-w-xs truncate">
                    {formatAddressDisplay(address)}
                  </div>
                </TableCell>
                <TableCell>{getStatusBadge(address.state)}</TableCell>
                <TableCell>{getIsDefaultBadge(address.isDefault)}</TableCell>
                <TableCell>
                  {address.createdAt ? format(new Date(address.createdAt), 'yyyy-MM-dd HH:mm', { locale: zhCN }) : '-'}
                </TableCell>
                <TableCell>
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleEditAddress(address)}
                      data-testid="edit-address-button"
                    >
                      <Edit className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleDeleteAddress(address.id)}
                      data-testid="delete-address-button"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
        {data?.data?.total && data.data.total > 0 && (
          <div className="mt-4">
            <DataTablePagination
              currentPage={searchParams.page}
              pageSize={searchParams.limit}
              totalCount={data.data.total}
              onPageChange={(page) => setSearchParams(prev => ({ ...prev, page }))}
              onPageSizeChange={(limit) => setSearchParams(prev => ({ ...prev, limit, page: 1 }))}
            />
          </div>
        )}
      </CardContent>
    </Card>
  );

  return (
    <div className="space-y-4">
      {/* 页面标题 */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-2xl font-bold">用户收货地址</h1>
          <p className="text-sm text-muted-foreground">管理用户的收货地址信息</p>
        </div>
        <Button onClick={handleCreateAddress}>
          <Plus className="mr-2 h-4 w-4" />
          创建收货地址
        </Button>
      </div>

      {/* 搜索区域 */}
      <Card>
        <CardHeader>
          <CardTitle>搜索筛选</CardTitle>
          <CardDescription>根据条件筛选收货地址</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex gap-4">
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="搜索姓名、手机号、地址..."
                  value={searchParams.search}
                  onChange={(e) => setSearchParams(prev => ({ ...prev, search: e.target.value }))}
                  className="pl-8"
                />
              </div>
            </div>
            <div className="w-64">
              <UserSelector
                value={searchParams.userId}
                onChange={(value) => setSearchParams(prev => ({ ...prev, userId: value }))}
                placeholder="选择用户"
                data-testid="search-user-selector"
              />
            </div>
            <Button onClick={handleSearch}>搜索</Button>
          </div>
        </CardContent>
      </Card>

      {/* 数据表格 */}
      {tableContent}

      {/* 创建/编辑模态框 */}
      <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
        <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {isCreateForm ? '创建收货地址' : '编辑收货地址'}
            </DialogTitle>
            <DialogDescription>
              {isCreateForm ? '创建一个新的收货地址' : '编辑现有收货地址信息'}
            </DialogDescription>
          </DialogHeader>

          {isCreateForm ? (
            <Form {...createForm}>
              <form onSubmit={createForm.handleSubmit(handleCreateSubmit)} className="space-y-4">
                <FormField
                  control={createForm.control}
                  name="userId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>用户<span className="text-red-500 ml-1">*</span></FormLabel>
                      <FormControl>
                        <UserSelector
                          value={field.value}
                          onChange={field.onChange}
                          placeholder="选择用户"
                          data-testid="create-user-selector"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <div className="grid grid-cols-2 gap-4">
                  <FormField
                    control={createForm.control}
                    name="name"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>收货人姓名<span className="text-red-500 ml-1">*</span></FormLabel>
                        <FormControl>
                          <Input placeholder="请输入收货人姓名" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={createForm.control}
                    name="phone"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>手机号<span className="text-red-500 ml-1">*</span></FormLabel>
                        <FormControl>
                          <Input placeholder="请输入手机号" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                <FormField
                  control={createForm.control}
                  name="address"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>详细地址<span className="text-red-500 ml-1">*</span></FormLabel>
                      <FormControl>
                        <Input placeholder="请输入详细地址" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <div className="space-y-2">
                  <FormLabel>四级地址选择<span className="text-red-500 ml-1">*</span></FormLabel>
                  <AreaSelect4Level
                    provinceValue={createForm.watch('receiverProvince') || 0}
                    cityValue={createForm.watch('receiverCity') || 0}
                    districtValue={createForm.watch('receiverDistrict') || 0}
                    townValue={createForm.watch('receiverTown') || 0}
                    onProvinceChange={(value) => createForm.setValue('receiverProvince', value)}
                    onCityChange={(value) => createForm.setValue('receiverCity', value)}
                    onDistrictChange={(value) => createForm.setValue('receiverDistrict', value)}
                    onTownChange={(value) => createForm.setValue('receiverTown', value)}
                    showLabels={false}
                  />
                </div>

                <FormField
                  control={createForm.control}
                  name="isDefault"
                  render={({ field }) => (
                    <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                      <div className="space-y-0.5">
                        <FormLabel className="text-base">设为默认地址</FormLabel>
                        <FormDescription>将此地址设为用户的默认收货地址</FormDescription>
                      </div>
                      <FormControl>
                        <Switch
                          checked={field.value === 1}
                          onCheckedChange={(checked) => field.onChange(checked ? 1 : 0)}
                        />
                      </FormControl>
                    </FormItem>
                  )}
                />

                <DialogFooter>
                  <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
                    取消
                  </Button>
                  <Button type="submit" disabled={createMutation.isPending}>
                    创建
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          ) : (
            <Form {...updateForm}>
              <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
                <FormField
                  control={updateForm.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>收货人姓名<span className="text-red-500 ml-1">*</span></FormLabel>
                      <FormControl>
                        <Input placeholder="请输入收货人姓名" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="phone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>手机号<span className="text-red-500 ml-1">*</span></FormLabel>
                      <FormControl>
                        <Input placeholder="请输入手机号" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="address"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>详细地址<span className="text-red-500 ml-1">*</span></FormLabel>
                      <FormControl>
                        <Input placeholder="请输入详细地址" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <div className="space-y-2">
                  <FormLabel>四级地址选择<span className="text-red-500 ml-1">*</span></FormLabel>
                  <AreaSelect4Level
                    provinceValue={updateForm.watch('receiverProvince') || 0}
                    cityValue={updateForm.watch('receiverCity') || 0}
                    districtValue={updateForm.watch('receiverDistrict') || 0}
                    townValue={updateForm.watch('receiverTown') || 0}
                    onProvinceChange={(value) => updateForm.setValue('receiverProvince', value)}
                    onCityChange={(value) => updateForm.setValue('receiverCity', value)}
                    onDistrictChange={(value) => updateForm.setValue('receiverDistrict', value)}
                    onTownChange={(value) => updateForm.setValue('receiverTown', value)}
                    showLabels={false}
                  />
                </div>

                <FormField
                  control={updateForm.control}
                  name="isDefault"
                  render={({ field }) => (
                    <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                      <div className="space-y-0.5">
                        <FormLabel className="text-base">设为默认地址</FormLabel>
                        <FormDescription>将此地址设为用户的默认收货地址</FormDescription>
                      </div>
                      <FormControl>
                        <Switch
                          checked={field.value === 1}
                          onCheckedChange={(checked) => field.onChange(checked ? 1 : 0)}
                        />
                      </FormControl>
                    </FormItem>
                  )}
                />

                <DialogFooter>
                  <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
                    取消
                  </Button>
                  <Button type="submit" disabled={updateMutation.isPending}>
                    更新
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          )}
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>确认删除</DialogTitle>
            <DialogDescription>
              确定要删除这个收货地址吗？此操作无法撤销。
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
              取消
            </Button>
            <Button variant="destructive" onClick={confirmDelete} disabled={deleteMutation.isPending}>
              删除
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};