import React, { useState } from 'react';
import { useQuery, useMutation } from '@tanstack/react-query';
import { Plus, Edit, Trash2, Search } from 'lucide-react';
import { format } from 'date-fns';
import { Input } from '@d8d/shared-ui-components/components/ui/input';
import { Button } from '@d8d/shared-ui-components/components/ui/button';
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 { Skeleton } from '@d8d/shared-ui-components/components/ui/skeleton';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@d8d/shared-ui-components/components/ui/dialog';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@d8d/shared-ui-components/components/ui/form';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { toast } from 'sonner';
import { DataTablePagination } from '@d8d/shared-ui-components/components/admin/DataTablePagination';
import { companyClientManager } from '../api/companyClient';
import { CreateCompanySchema, UpdateCompanySchema } from '@d8d/allin-company-module/schemas';
import { PlatformSelector } from '@d8d/allin-platform-management-ui/components';
import type {
  CompanyResponse,
  CompanyListResponse,
  SearchCompanyResponse,
  CreateCompanyRequest,
  UpdateCompanyRequest
} from '../types';

interface CompanySearchParams {
  page: number;
  limit: number;
  search: string;
}

const CompanyManagement: React.FC = () => {
  const [searchParams, setSearchParams] = useState<CompanySearchParams>({ page: 1, limit: 10, search: '' });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isCreateForm, setIsCreateForm] = useState(true);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [companyToDelete, setCompanyToDelete] = useState<number | null>(null);

  // 表单实例
  const createForm = useForm<CreateCompanyRequest>({
    resolver: zodResolver(CreateCompanySchema),
    defaultValues: {
      platformId: undefined,
      companyName: '',
      contactPerson: undefined,
      contactPhone: undefined,
      contactEmail: undefined,
      address: undefined
    }
  });

  const updateForm = useForm<UpdateCompanyRequest>({
    resolver: zodResolver(UpdateCompanySchema),
    defaultValues: {}
  });

  // 数据查询
  const { data, isLoading, refetch } = useQuery<CompanyListResponse | SearchCompanyResponse>({
    queryKey: ['companies', searchParams],
    queryFn: async () => {
      const skip = (searchParams.page - 1) * searchParams.limit;
      const take = searchParams.limit;

      let res;
      if (searchParams.search.trim()) {
        res = await companyClientManager.get().searchCompanies.$get({
          query: {
            name: searchParams.search,
            skip,
            take
          }
        });
      } else {
        res = await companyClientManager.get().getAllCompanies.$get({
          query: { skip, take }
        });
      }

      if (res.status !== 200) throw new Error('获取公司列表失败');
      return await res.json();
    }
  });

  // 创建公司
  const createMutation = useMutation({
    mutationFn: async (data: CreateCompanyRequest) => {
      const res = await companyClientManager.get().createCompany.$post({ json: data });
      if (res.status !== 200) {
        // 尝试从API响应中提取错误信息
        let errorMessage = `创建公司失败 (${res.status})`;
        try {
          const errorData = await res.json();
          errorMessage = errorData.message || errorMessage;
        } catch {
          // 如果无法解析JSON，保持默认错误消息
        }
        throw new Error(errorMessage);
      }
      return await res.json();
    },
    onSuccess: () => {
      toast.success('公司创建成功');
      setIsModalOpen(false);
      createForm.reset();
      refetch();
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : '创建公司失败');
    }
  });

  // 更新公司
  const updateMutation = useMutation({
    mutationFn: async (data: UpdateCompanyRequest) => {
      const res = await companyClientManager.get().updateCompany.$post({
        json: data
      });
      if (res.status !== 200) {
        // 尝试从API响应中提取错误信息
        let errorMessage = `更新公司失败 (${res.status})`;
        try {
          const errorData = await res.json();
          errorMessage = errorData.message || errorMessage;
        } catch {
          // 如果无法解析JSON，保持默认错误消息
        }
        throw new Error(errorMessage);
      }
      return await res.json();
    },
    onSuccess: () => {
      toast.success('公司更新成功');
      setIsModalOpen(false);
      refetch();
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : '更新公司失败');
    }
  });

  // 删除公司
  const deleteMutation = useMutation({
    mutationFn: async (id: number) => {
      const res = await companyClientManager.get().deleteCompany.$post({
        json: { id }
      });
      if (res.status !== 200) {
        // 尝试从API响应中提取错误信息
        let errorMessage = `删除公司失败 (${res.status})`;
        try {
          const errorData = await res.json();
          errorMessage = errorData.message || errorMessage;
        } catch {
          // 如果无法解析JSON，保持默认错误消息
        }
        throw new Error(errorMessage);
      }
      return await res.json();
    },
    onSuccess: () => {
      toast.success('公司删除成功');
      setDeleteDialogOpen(false);
      setCompanyToDelete(null);
      refetch();
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : '删除公司失败');
    }
  });

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

  const handleUpdateSubmit = (data: UpdateCompanyRequest) => {
    updateMutation.mutate(data);
  };

  const handleEdit = (company: CompanyResponse) => {
    setIsCreateForm(false);
    updateForm.reset({
      id: company.id,
      platformId: company.platformId,
      companyName: company.companyName,
      contactPerson: company.contactPerson || undefined,
      contactPhone: company.contactPhone || undefined,
      contactEmail: company.contactEmail || undefined,
      address: company.address || undefined
    });
    setIsModalOpen(true);
  };

  const handleDelete = (id: number) => {
    setCompanyToDelete(id);
    setDeleteDialogOpen(true);
  };

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

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    refetch();
  };

  const handlePageChange = (page: number) => {
    setSearchParams(prev => ({ ...prev, page }));
  };

  const handleLimitChange = (limit: number) => {
    setSearchParams(prev => ({ ...prev, limit, page: 1 }));
  };

  const companyList = data?.data || [];
  const total = data?.total || 0;

  return (
    <div className="container mx-auto py-6">
      <Card>
        <CardHeader>
          <CardTitle>公司管理</CardTitle>
          <CardDescription>管理所有公司信息，包括创建、编辑、删除和搜索功能</CardDescription>
        </CardHeader>
        <CardContent>
          {/* 搜索和操作栏 */}
          <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6">
            <form onSubmit={handleSearch} className="flex items-center gap-2 w-full md:w-auto">
              <Input
                placeholder="搜索公司名称..."
                value={searchParams.search}
                onChange={(e) => setSearchParams(prev => ({ ...prev, search: e.target.value }))}
                className="w-full md:w-64"
                data-testid="search-company-input"
              />
              <Button type="submit" size="icon" data-testid="search-company-button">
                <Search className="h-4 w-4" />
              </Button>
            </form>
            <Button onClick={() => {
              setIsCreateForm(true);
              createForm.reset();
              setIsModalOpen(true);
            }} data-testid="create-company-button">
              <Plus className="h-4 w-4 mr-2" />
              创建公司
            </Button>
          </div>

          {/* 公司表格 */}
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>公司名称</TableHead>
                  <TableHead>平台</TableHead>
                  <TableHead>联系人</TableHead>
                  <TableHead>联系电话</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>创建时间</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {isLoading ? (
                  Array.from({ length: 5 }).map((_, i) => (
                    <TableRow key={i}>
                      <TableCell><Skeleton className="h-4 w-32" /></TableCell>
                      <TableCell><Skeleton className="h-4 w-24" /></TableCell>
                      <TableCell><Skeleton className="h-4 w-20" /></TableCell>
                      <TableCell><Skeleton className="h-4 w-24" /></TableCell>
                      <TableCell><Skeleton className="h-4 w-16" /></TableCell>
                      <TableCell><Skeleton className="h-4 w-32" /></TableCell>
                      <TableCell><Skeleton className="h-8 w-16" /></TableCell>
                    </TableRow>
                  ))
                ) : companyList.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                      暂无数据
                    </TableCell>
                  </TableRow>
                ) : (
                  companyList.map((company) => (
                    <TableRow key={company.id}>
                      <TableCell className="font-medium">{company.companyName}</TableCell>
                      <TableCell>{company.platform?.platformName || '未知平台'}</TableCell>
                      <TableCell>{company.contactPerson}</TableCell>
                      <TableCell>{company.contactPhone}</TableCell>
                      <TableCell>
                        <span className={`px-2 py-1 rounded-full text-xs ${company.status === 1 ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'}`}>
                          {company.status === 1 ? '启用' : '禁用'}
                        </span>
                      </TableCell>
                      <TableCell>{format(new Date(company.createTime), 'yyyy-MM-dd HH:mm')}</TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleEdit(company)}
                            data-testid={`edit-company-button-${company.id}`}
                          >
                            <Edit className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleDelete(company.id)}
                            disabled={company.status === 0}
                            data-testid={`delete-company-button-${company.id}`}
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>

          {/* 分页 */}
          {!isLoading && companyList.length > 0 && (
            <div className="mt-4">
              <DataTablePagination
                currentPage={searchParams.page}
                totalCount={total}
                pageSize={searchParams.limit}
                onPageChange={(page, pageSize) => {
                  handlePageChange(page);
                  if (pageSize !== searchParams.limit) {
                    handleLimitChange(pageSize);
                  }
                }}
              />
            </div>
          )}
        </CardContent>
      </Card>

      {/* 创建/编辑公司模态框 */}
      <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle data-testid="company-modal-title">
              {isCreateForm ? '创建公司' : '编辑公司'}
            </DialogTitle>
            <DialogDescription>
              {isCreateForm ? '填写公司信息以创建新公司' : '修改公司信息'}
            </DialogDescription>
          </DialogHeader>
          {isCreateForm ? (
            <Form {...createForm}>
              <form onSubmit={createForm.handleSubmit(handleCreateSubmit)} className="space-y-4">
                <FormField
                  control={createForm.control}
                  name="platformId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>平台（可选）</FormLabel>
                      <FormControl>
                        <PlatformSelector
                          value={field.value}
                          onChange={field.onChange}
                          placeholder="选择平台"
                          testId="create-company-platform-selector"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={createForm.control}
                  name="companyName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>公司名称</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="请输入公司名称"
                          {...field}
                          data-testid="create-company-name-input"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={createForm.control}
                  name="contactPerson"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>联系人（可选）</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="请输入联系人"
                          {...field}
                          data-testid="create-company-contact-person-input"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={createForm.control}
                  name="contactPhone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>联系电话（可选）</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="请输入联系电话"
                          {...field}
                          data-testid="create-company-contact-phone-input"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={createForm.control}
                  name="contactEmail"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>联系邮箱（可选）</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="请输入联系邮箱"
                          type="email"
                          {...field}
                          data-testid="create-company-contact-email-input"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={createForm.control}
                  name="address"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>地址（可选）</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="请输入地址"
                          {...field}
                          data-testid="create-company-address-input"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <DialogFooter>
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => setIsModalOpen(false)}
                    data-testid="cancel-company-button"
                  >
                    取消
                  </Button>
                  <Button
                    type="submit"
                    disabled={createMutation.isPending}
                    data-testid="submit-create-company-button"
                  >
                    {createMutation.isPending ? '创建中...' : '创建'}
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          ) : (
            <Form {...updateForm}>
              <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
                <FormField
                  control={updateForm.control}
                  name="platformId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>平台（可选）</FormLabel>
                      <FormControl>
                        <PlatformSelector
                          value={field.value}
                          onChange={field.onChange}
                          placeholder="选择平台"
                          testId="edit-company-platform-selector"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={updateForm.control}
                  name="companyName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>公司名称</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="请输入公司名称"
                          {...field}
                          data-testid="edit-company-name-input"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={updateForm.control}
                  name="contactPerson"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>联系人（可选）</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="请输入联系人"
                          {...field}
                          data-testid="edit-company-contact-person-input"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={updateForm.control}
                  name="contactPhone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>联系电话（可选）</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="请输入联系电话"
                          {...field}
                          data-testid="edit-company-contact-phone-input"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={updateForm.control}
                  name="contactEmail"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>联系邮箱（可选）</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="请输入联系邮箱"
                          type="email"
                          {...field}
                          data-testid="edit-company-contact-email-input"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={updateForm.control}
                  name="address"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>地址（可选）</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="请输入地址"
                          {...field}
                          data-testid="edit-company-address-input"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <DialogFooter>
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => setIsModalOpen(false)}
                    data-testid="cancel-edit-company-button"
                  >
                    取消
                  </Button>
                  <Button
                    type="submit"
                    disabled={updateMutation.isPending}
                    data-testid="submit-edit-company-button"
                  >
                    {updateMutation.isPending ? '更新中...' : '更新'}
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          )}
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <DialogContent className="sm:max-w-[400px]">
          <DialogHeader>
            <DialogTitle>确认删除</DialogTitle>
            <DialogDescription>
              确定要删除这个公司吗？此操作不可恢复。
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setDeleteDialogOpen(false)}
              data-testid="cancel-delete-company-button"
            >
              取消
            </Button>
            <Button
              variant="destructive"
              onClick={confirmDelete}
              disabled={deleteMutation.isPending}
              data-testid="confirm-delete-company-button"
            >
              {deleteMutation.isPending ? '删除中...' : '确认删除'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default CompanyManagement;