import React, { useState, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@d8d/shared-ui-components/components/ui/card';
import { Input } from '@d8d/shared-ui-components/components/ui/input';
import { Label } from '@d8d/shared-ui-components/components/ui/label';
import { Skeleton } from '@d8d/shared-ui-components/components/ui/skeleton';
import { Alert, AlertDescription } from '@d8d/shared-ui-components/components/ui/alert';
import { Calculator, AlertCircle } from 'lucide-react';
import { AreaSelect } from '@d8d/area-management-ui/components';
import { salaryClientManager } from '../api/salaryClient';
import type { SalaryByProvinceCityResponse } from '../api/types';

export interface SalarySelectorProps {
  value?: {
    provinceId?: number;
    cityId?: number;
    salary?: number;
    salaryDetail?: SalaryByProvinceCityResponse;
  };
  onChange?: (value: {
    provinceId?: number;
    cityId?: number;
    salary?: number;
    salaryDetail?: SalaryByProvinceCityResponse;
  }) => void;
  disabled?: boolean;
  allowManualAdjust?: boolean;
  required?: boolean;
  className?: string;
}

const SalarySelector: React.FC<SalarySelectorProps> = ({
  value = {},
  onChange,
  disabled = false,
  allowManualAdjust = true,
  required = false,
  className = ''
}) => {
  const [areaValue, setAreaValue] = useState<{ provinceId?: number; cityId?: number; districtId?: number }>({
    provinceId: value.provinceId,
    cityId: value.cityId
  });
  const [manualSalary, setManualSalary] = useState<number | undefined>(value.salary);
  const [isManualMode, setIsManualMode] = useState(false);

  // 查询薪资详情
  const { data: salaryData, isLoading, isError, refetch } = useQuery({
    queryKey: ['salary-by-province-city', areaValue.provinceId, areaValue.cityId],
    queryFn: async () => {
      if (!areaValue.provinceId || !areaValue.cityId) {
        return null;
      }

      const res = await salaryClientManager.get().byProvinceCity.$get({
        query: {
          provinceId: areaValue.provinceId,
          cityId: areaValue.cityId
        }
      });

      if (res.status === 404) {
        return null; // 薪资记录不存在
      }

      if (res.status !== 200) {
        throw new Error('查询薪资失败');
      }

      return await res.json();
    },
    enabled: !!areaValue.provinceId && !!areaValue.cityId && !isManualMode,
    staleTime: 5 * 60 * 1000, // 5分钟缓存
    gcTime: 10 * 60 * 1000, // 10分钟垃圾回收时间
  });

  // 计算总薪资
  const calculateTotalSalary = (salary: SalaryByProvinceCityResponse): number => {
    if (!salary) return 0;
    return salary.basicSalary + (salary.allowance || 0) - (salary.insurance || 0) - (salary.housingFund || 0);
  };

  // 处理区域选择变化
  const handleAreaChange = (newAreaValue: { provinceId?: number; cityId?: number; districtId?: number }) => {
    setAreaValue(newAreaValue);
    setIsManualMode(false);

    if (newAreaValue.provinceId && newAreaValue.cityId) {
      const newValue = {
        provinceId: newAreaValue.provinceId,
        cityId: newAreaValue.cityId,
        salary: undefined,
        salaryDetail: undefined
      };
      onChange?.(newValue);
    }
  };

  // 处理手动薪资输入
  const handleManualSalaryChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = parseFloat(e.target.value) || 0;
    setManualSalary(value);

    onChange?.({
      provinceId: areaValue.provinceId,
      cityId: areaValue.cityId,
      salary: value,
      salaryDetail: undefined
    });
  };

  // 切换手动模式
  const toggleManualMode = () => {
    const newManualMode = !isManualMode;
    setIsManualMode(newManualMode);

    if (newManualMode) {
      // 切换到手动模式，使用查询到的薪资或0作为默认值
      const defaultSalary = salaryData ? calculateTotalSalary(salaryData) : 0;
      setManualSalary(defaultSalary);

      onChange?.({
        provinceId: areaValue.provinceId,
        cityId: areaValue.cityId,
        salary: defaultSalary,
        salaryDetail: undefined
      });
    } else {
      // 切换回自动模式，重新查询
      if (areaValue.provinceId && areaValue.cityId) {
        refetch();
      }
    }
  };

  // 同步外部值变化
  useEffect(() => {
    setAreaValue({
      provinceId: value.provinceId,
      cityId: value.cityId
    });
    setManualSalary(value.salary);

    // 如果外部提供了薪资但没有薪资详情，可能是手动模式
    if (value.salary !== undefined && !value.salaryDetail) {
      setIsManualMode(true);
    }
  }, [value.provinceId, value.cityId, value.salary, value.salaryDetail]);

  // 薪资详情变化时通知父组件
  useEffect(() => {
    if (salaryData && !isManualMode) {
      onChange?.({
        provinceId: areaValue.provinceId,
        cityId: areaValue.cityId,
        salary: calculateTotalSalary(salaryData),
        salaryDetail: salaryData
      });
    }
  }, [salaryData, isManualMode]);

  const currentSalary = salaryData || value.salaryDetail;
  const totalSalary = isManualMode ? (manualSalary || 0) : (currentSalary ? calculateTotalSalary(currentSalary) : 0);

  return (
    <div className={`space-y-4 ${className}`}>
      {/* 区域选择器 */}
      <div>
        <Label className="mb-2 block">
          选择区域{required && <span className="text-destructive">*</span>}
        </Label>
        <AreaSelect
          value={areaValue}
          onChange={handleAreaChange}
          disabled={disabled}
          required={required}
        />
      </div>

      {/* 薪资信息显示 */}
      {areaValue.provinceId && areaValue.cityId && (
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="flex items-center gap-2 text-lg">
              <Calculator className="h-5 w-5" />
              薪资信息
            </CardTitle>
            <CardDescription>
              {isManualMode ? '手动调整薪资模式' : '自动查询薪资模式'}
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {isLoading ? (
              <div className="space-y-2">
                <Skeleton className="h-4 w-full" />
                <Skeleton className="h-4 w-3/4" />
                <Skeleton className="h-4 w-1/2" />
              </div>
            ) : isError ? (
              <Alert variant="destructive">
                <AlertCircle className="h-4 w-4" />
                <AlertDescription>
                  查询薪资信息失败，请检查网络连接或稍后重试
                </AlertDescription>
              </Alert>
            ) : isManualMode ? (
              // 手动模式
              <div className="space-y-4">
                <div>
                  <Label htmlFor="manual-salary" className="mb-2 block">
                    手动输入薪资
                  </Label>
                  <Input
                    id="manual-salary"
                    type="number"
                    step="0.01"
                    min="0"
                    value={manualSalary || ''}
                    onChange={handleManualSalaryChange}
                    disabled={disabled}
                    placeholder="请输入薪资金额"
                  />
                </div>
                <div className="text-sm text-muted-foreground">
                  <p>当前为手动模式，薪资不会根据区域自动查询</p>
                  <p className="font-medium mt-1">总薪资: ¥{totalSalary.toFixed(2)}</p>
                </div>
              </div>
            ) : currentSalary ? (
              // 自动模式 - 有薪资数据
              <div className="space-y-3">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label className="text-sm text-muted-foreground">基本工资</Label>
                    <p className="text-lg font-medium">¥{currentSalary.basicSalary.toFixed(2)}</p>
                  </div>
                  <div>
                    <Label className="text-sm text-muted-foreground">津贴补贴</Label>
                    <p className="text-lg font-medium">¥{(currentSalary.allowance || 0).toFixed(2)}</p>
                  </div>
                  <div>
                    <Label className="text-sm text-muted-foreground">保险费用</Label>
                    <p className="text-lg font-medium">¥{(currentSalary.insurance || 0).toFixed(2)}</p>
                  </div>
                  <div>
                    <Label className="text-sm text-muted-foreground">公积金</Label>
                    <p className="text-lg font-medium">¥{(currentSalary.housingFund || 0).toFixed(2)}</p>
                  </div>
                </div>
                <div className="pt-3 border-t">
                  <div className="flex justify-between items-center">
                    <Label className="text-base">总薪资</Label>
                    <p className="text-2xl font-bold text-primary">¥{totalSalary.toFixed(2)}</p>
                  </div>
                  <p className="text-sm text-muted-foreground mt-1">
                    计算公式：基本工资 + 津贴 - 保险 - 公积金
                  </p>
                </div>
              </div>
            ) : (
              // 自动模式 - 无薪资数据
              <Alert>
                <AlertCircle className="h-4 w-4" />
                <AlertDescription className="space-y-2">
                  <p>该区域暂无薪资记录</p>
                  {allowManualAdjust && (
                    <p className="text-sm">
                      您可以切换到手动模式输入薪资，或联系管理员添加该区域的薪资标准
                    </p>
                  )}
                </AlertDescription>
              </Alert>
            )}

            {/* 模式切换按钮 */}
            {allowManualAdjust && !isLoading && !isError && (
              <div className="pt-4 border-t">
                <button
                  type="button"
                  onClick={toggleManualMode}
                  disabled={disabled}
                  className="text-sm text-primary hover:underline focus:outline-none focus:underline"
                >
                  {isManualMode ? '切换回自动查询模式' : '切换到手动调整模式'}
                </button>
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* 区域未选择提示 */}
      {(!areaValue.provinceId || !areaValue.cityId) && (
        <Alert>
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>
            请先选择省份和城市以查询薪资信息
          </AlertDescription>
        </Alert>
      )}
    </div>
  );
};

export default SalarySelector;