'use client';

import { useState } from 'react';
import { PageHeader } from '@/components/layout/page-header';
import { useConfigs, useUpdateConfig, useTransferEnabled, useSetTransferEnabled } from '@/features/configs/hooks/use-configs';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Skeleton } from '@/components/ui/skeleton';
import { Pencil, Save, X } from 'lucide-react';
import type { SystemConfig } from '@/types/config';

const categoryLabels: Record<string, string> = {
  mining: '挖矿配置',
  trading: '交易配置',
  distribution: '分配配置',
  system: '系统配置',
};

export default function ConfigsPage() {
  const { data: configs, isLoading } = useConfigs();
  const { data: transferEnabled, isLoading: transferLoading } = useTransferEnabled();
  const updateConfig = useUpdateConfig();
  const setTransferEnabled = useSetTransferEnabled();

  const [editingConfig, setEditingConfig] = useState<SystemConfig | null>(null);
  const [editValue, setEditValue] = useState('');

  const handleEdit = (config: SystemConfig) => {
    setEditingConfig(config);
    setEditValue(config.configValue);
  };

  const handleSave = () => {
    if (editingConfig) {
      updateConfig.mutate({ key: editingConfig.configKey, value: editValue });
      setEditingConfig(null);
    }
  };

  const handleTransferToggle = (checked: boolean) => {
    setTransferEnabled.mutate(checked);
  };

  const groupedConfigs = configs?.reduce(
    (acc, config) => {
      const category = config.category || 'system';
      if (!acc[category]) {
        acc[category] = [];
      }
      acc[category].push(config);
      return acc;
    },
    {} as Record<string, SystemConfig[]>
  );

  return (
    <div className="space-y-6">
      <PageHeader title="配置管理" description="管理系统配置参数" />

      <Card>
        <CardHeader>
          <CardTitle className="text-lg">划转开关</CardTitle>
          <CardDescription>控制用户是否可以进行挖矿账户到交易账户的划转</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-between">
            <div>
              <p className="font-medium">允许用户划转</p>
              <p className="text-sm text-muted-foreground">开启后用户可以将挖矿获得的积分股划转到交易账户</p>
            </div>
            {transferLoading ? (
              <Skeleton className="h-6 w-11" />
            ) : (
              <Switch
                checked={transferEnabled}
                onCheckedChange={handleTransferToggle}
                disabled={setTransferEnabled.isPending}
              />
            )}
          </div>
        </CardContent>
      </Card>

      {isLoading ? (
        <Card>
          <CardContent className="p-6">
            <Skeleton className="h-64 w-full" />
          </CardContent>
        </Card>
      ) : (
        Object.entries(groupedConfigs || {}).map(([category, configs]) => (
          <Card key={category}>
            <CardHeader>
              <CardTitle className="text-lg">{categoryLabels[category] || category}</CardTitle>
            </CardHeader>
            <CardContent className="p-0">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>配置项</TableHead>
                    <TableHead>描述</TableHead>
                    <TableHead>当前值</TableHead>
                    <TableHead className="w-[100px]">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {configs.map((config) => (
                    <TableRow key={config.configKey}>
                      <TableCell className="font-mono">{config.configKey}</TableCell>
                      <TableCell className="text-muted-foreground">{config.description}</TableCell>
                      <TableCell className="font-mono">{config.configValue}</TableCell>
                      <TableCell>
                        {config.isEditable && (
                          <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => handleEdit(config)}>
                            <Pencil className="h-4 w-4" />
                          </Button>
                        )}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        ))
      )}

      <Dialog open={!!editingConfig} onOpenChange={() => setEditingConfig(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>编辑配置</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>配置项</Label>
              <Input value={editingConfig?.configKey || ''} disabled />
            </div>
            <div className="space-y-2">
              <Label>描述</Label>
              <p className="text-sm text-muted-foreground">{editingConfig?.description}</p>
            </div>
            <div className="space-y-2">
              <Label>配置值</Label>
              <Input value={editValue} onChange={(e) => setEditValue(e.target.value)} />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setEditingConfig(null)}>
              <X className="h-4 w-4 mr-2" />
              取消
            </Button>
            <Button onClick={handleSave} disabled={updateConfig.isPending}>
              <Save className="h-4 w-4 mr-2" />
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
