import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Plus, Search, Edit, Trash2, MapPin } from 'lucide-react';
import { Button } from '@/client/components/ui/button';
import { Input } from '@/client/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/client/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/client/components/ui/table';
import { Badge } from '@/client/components/ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/client/components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/client/components/ui/select';
import { toast } from 'sonner';
import { locationClient, areaClient } from '@/client/api';
import { LocationForm } from '../components/LocationForm';

interface Location {
  id: number;
  name: string;
  address: string;
  province: {
    id: number;
    name: string;
    code: string;
  } | null;
  city: {
    id: number;
    name: string;
    code: string;
  } | null;
  district: {
    id: number;
    name: string;
    code: string;
  } | null;
  latitude?: number | null;
  longitude?: number | null;
  isDisabled: number;
  createdAt: string;
  updatedAt: string;
}

interface SearchParams {
  keyword?: string;
  areaId?: number;
  isDisabled?: number;
  page?: number;
  pageSize?: number;
}

/**
 * 地点管理页面
 */
export const LocationsPage = () => {
  const queryClient = useQueryClient();
  const [searchParams, setSearchParams] = useState<SearchParams>({
    page: 1,
    pageSize: 20,
  });
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [editingLocation, setEditingLocation] = useState<Location | null>(null);

  // 获取地点列表
  const { data: locationsData, isLoading } = useQuery({
    queryKey: ['locations', searchParams],
    queryFn: async () => {
      const res = await locationClient.$get({ query: searchParams });
      if (res.status !== 200) throw new Error('获取地点列表失败');
      return await res.json();
    },
  });

  // 获取区域列表
  const { data: areasData } = useQuery({
    queryKey: ['areas'],
    queryFn: async () => {
      const res = await areaClient.$get({ query: { pageSize: 100 } });
      if (res.status !== 200) throw new Error('获取区域列表失败');
      return await res.json();
    },
  });

  // 创建地点
  const createMutation = useMutation({
    mutationFn: async (data: any) => {
      const res = await locationClient.$post({ json: data });
      if (res.status !== 201) throw new Error('创建地点失败');
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['locations'] });
      setIsCreateDialogOpen(false);
      toast.success('地点已成功创建');
    },
    onError: (error: Error) => {
      toast.error(error.message || '创建地点失败');
    },
  });

  // 更新地点
  const updateMutation = useMutation({
    mutationFn: async ({ id, data }: { id: number; data: any }) => {
      const res = await locationClient[':id'].$put({ param: { id }, json: data });
      if (res.status !== 200) throw new Error('更新地点失败');
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['locations'] });
      setEditingLocation(null);
      toast.success('地点已成功更新');
    },
    onError: (error: Error) => {
      toast.error(error.message || '更新地点失败');
    },
  });

  // 删除地点
  const deleteMutation = useMutation({
    mutationFn: async (id: number) => {
      const res = await locationClient[':id'].$delete({ param: { id } });
      if (res.status !== 204) throw new Error('删除地点失败');
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['locations'] });
      toast.success('地点已成功删除');
    },
    onError: (error: Error) => {
      toast.error(error.message || '删除地点失败');
    },
  });

  // 切换状态
  const toggleStatusMutation = useMutation({
    mutationFn: async ({ id, isDisabled }: { id: number; isDisabled: number }) => {
      const res = await locationClient[':id'].$put({ param: { id }, json: { isDisabled } });
      if (res.status !== 200) throw new Error('更新状态失败');
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['locations'] });
      toast.success('地点状态已更新');
    },
    onError: (error: Error) => {
      toast.error(error.message || '更新状态失败');
    },
  });

  const handleSearch = (keyword: string) => {
    setSearchParams(prev => ({
      ...prev,
      keyword: keyword || undefined,
      page: 1,
    }));
  };

  const handleAreaFilter = (areaId: string) => {
    setSearchParams(prev => ({
      ...prev,
      areaId: areaId && areaId !== 'all' ? parseInt(areaId) : undefined,
      page: 1,
    }));
  };

  const handleStatusFilter = (status: string) => {
    setSearchParams(prev => ({
      ...prev,
      isDisabled: status && status !== 'all' ? parseInt(status) : undefined,
      page: 1,
    }));
  };

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

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

  const handleDelete = (id: number) => {
    if (confirm('确定要删除这个地点吗？')) {
      deleteMutation.mutate(id);
    }
  };

  const handleToggleStatus = (location: Location) => {
    const newStatus = location.isDisabled === 0 ? 1 : 0;
    toggleStatusMutation.mutate({ id: location.id, isDisabled: newStatus });
  };

  const handleEdit = (location: Location) => {
    setEditingLocation(location);
  };

  const locations = locationsData?.data || [];
  const pagination = locationsData?.pagination;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">地点管理</h1>
          <p className="text-muted-foreground">
            管理系统中的地点信息
          </p>
        </div>
        <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="h-4 w-4 mr-2" />
              新建地点
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl">
            <DialogHeader>
              <DialogTitle>新建地点</DialogTitle>
              <DialogDescription>
                添加一个新的地点到系统中
              </DialogDescription>
            </DialogHeader>
            <LocationForm
              onSubmit={handleCreate}
              isLoading={createMutation.isPending}
              areas={areasData?.data || []}
            />
          </DialogContent>
        </Dialog>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>地点列表</CardTitle>
          <CardDescription>
            管理所有地点信息，包括地址、坐标和所属区域
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex flex-col gap-4">
            {/* 搜索和筛选 */}
            <div className="flex flex-col sm:flex-row 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="搜索地点名称或地址..."
                    className="pl-8"
                    onChange={(e) => handleSearch(e.target.value)}
                  />
                </div>
              </div>
              <Select onValueChange={handleAreaFilter}>
                <SelectTrigger className="w-[180px]">
                  <SelectValue placeholder="选择区域" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部区域</SelectItem>
                  {areasData?.data?.map((area: any) => (
                    <SelectItem key={area.id} value={area.id.toString()}>
                      {area.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Select onValueChange={handleStatusFilter}>
                <SelectTrigger className="w-[180px]">
                  <SelectValue placeholder="状态筛选" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="0">启用</SelectItem>
                  <SelectItem value="1">禁用</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 地点表格 */}
            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>地点名称</TableHead>
                    <TableHead>地址</TableHead>
                    <TableHead>所属区域</TableHead>
                    <TableHead>坐标</TableHead>
                    <TableHead>状态</TableHead>
                    <TableHead>创建时间</TableHead>
                    <TableHead className="text-right">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {isLoading ? (
                    <TableRow>
                      <TableCell colSpan={7} className="text-center py-8">
                        加载中...
                      </TableCell>
                    </TableRow>
                  ) : locations.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={7} className="text-center py-8">
                        <div className="flex flex-col items-center gap-2">
                          <MapPin className="h-8 w-8 text-muted-foreground" />
                          <p className="text-muted-foreground">暂无地点数据</p>
                        </div>
                      </TableCell>
                    </TableRow>
                  ) : (
                    locations.map((location: Location) => (
                      <TableRow key={location.id}>
                        <TableCell className="font-medium">{location.name}</TableCell>
                        <TableCell>{location.address}</TableCell>
                        <TableCell>
                          <div className="flex flex-col gap-1">
                            {location.province && (
                              <Badge variant="outline">
                                {location.province.name}
                              </Badge>
                            )}
                            {location.city && (
                              <Badge variant="outline">
                                {location.city.name}
                              </Badge>
                            )}
                            {location.district && (
                              <Badge variant="outline">
                                {location.district.name}
                              </Badge>
                            )}
                          </div>
                        </TableCell>
                        <TableCell>
                          {location.latitude && location.longitude ? (
                            <span className="text-sm text-muted-foreground">
                              {location.latitude.toFixed(6)}, {location.longitude.toFixed(6)}
                            </span>
                          ) : (
                            <span className="text-sm text-muted-foreground">未设置</span>
                          )}
                        </TableCell>
                        <TableCell>
                          <Badge variant={location.isDisabled === 0 ? "default" : "secondary"}>
                            {location.isDisabled === 0 ? "启用" : "禁用"}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          {new Date(location.createdAt).toLocaleDateString()}
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="flex justify-end gap-2">
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => handleEdit(location)}
                            >
                              <Edit className="h-4 w-4" />
                            </Button>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => handleToggleStatus(location)}
                            >
                              {location.isDisabled === 0 ? "禁用" : "启用"}
                            </Button>
                            <Button
                              variant="destructive"
                              size="sm"
                              onClick={() => handleDelete(location.id)}
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>

            {/* 分页 */}
            {pagination && pagination.total > 0 && (
              <div className="flex items-center justify-between">
                <div className="text-sm text-muted-foreground">
                  显示第 {(pagination.current - 1) * pagination.pageSize + 1} 到{' '}
                  {Math.min(pagination.current * pagination.pageSize, pagination.total)} 条，
                  共 {pagination.total} 条记录
                </div>
                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    disabled={pagination.current <= 1}
                    onClick={() => setSearchParams(prev => ({ ...prev, page: prev.page! - 1 }))}
                  >
                    上一页
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    disabled={pagination.current >= Math.ceil(pagination.total / pagination.pageSize)}
                    onClick={() => setSearchParams(prev => ({ ...prev, page: prev.page! + 1 }))}
                  >
                    下一页
                  </Button>
                </div>
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* 编辑对话框 */}
      <Dialog open={!!editingLocation} onOpenChange={(open) => !open && setEditingLocation(null)}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>编辑地点</DialogTitle>
            <DialogDescription>
              修改地点信息
            </DialogDescription>
          </DialogHeader>
          {editingLocation && (
            <LocationForm
              onSubmit={handleUpdate}
              isLoading={updateMutation.isPending}
              areas={areasData?.data || []}
              initialData={editingLocation}
            />
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
};