import { useMemo, useState, type FormEvent } from 'react';
import { Pencil, Plus, RotateCcw, Trash2 } from 'lucide-react';
import type { CatalogProvider, CatalogProviderUpsertRequest } from '@easyai-ai-gateway/contracts';
import { Badge, Button, Card, CardContent, CardHeader, CardTitle, ConfirmDialog, FormDialog, Input, Label, Select } from '../../components/ui';
import type { LoadState } from '../../types';

type ProviderForm = {
  code: string;
  displayName: string;
  providerType: string;
  iconPath: string;
  defaultBaseUrl: string;
  defaultAuthType: string;
  source: string;
  status: string;
};

const emptyForm: ProviderForm = {
  code: '',
  displayName: '',
  providerType: 'openai',
  iconPath: '',
  defaultBaseUrl: '',
  defaultAuthType: 'APIKey',
  source: 'gateway',
  status: 'active',
};

const defaultSpecTypes = [
  'openai',
  'azure',
  'google-gemini',
  'LiblibAI',
  'keling',
  'runninghub',
  'blackforest',
  'dify',
  'ollama',
  'jimeng',
  'volces',
  'tripo3d',
  'tencent-hunyuan',
  'tencent-hunyuan-image',
  'tencent-hunyuan-video',
  'suno',
  'minimax',
  'midjourney',
  'tencent-lke',
  'easyai',
  'aliyun-bailian',
  'universal',
  'newapi',
  'vidu',
  'mock-test',
  'n8n',
];
const providerStatuses = ['active', 'deprecated', 'hidden'];
const authTypeOptions = ['APIKey', 'Token', 'AccessKey-SecretKey', 'none'];

export function ProviderManagementPanel(props: {
  message: string;
  providers: CatalogProvider[];
  state: LoadState;
  onDeleteProvider: (providerId: string) => Promise<void>;
  onSaveProvider: (input: CatalogProviderUpsertRequest, providerId?: string) => Promise<void>;
}) {
  const [editingId, setEditingId] = useState('');
  const [form, setForm] = useState<ProviderForm>(emptyForm);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [pendingDeleteProvider, setPendingDeleteProvider] = useState<CatalogProvider | null>(null);
  const editingProvider = useMemo(
    () => props.providers.find((item) => item.id === editingId),
    [editingId, props.providers],
  );
  const specTypes = useMemo(
    () => Array.from(new Set([...defaultSpecTypes, ...props.providers.map((item) => item.providerType).filter(Boolean)])),
    [props.providers],
  );

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const payload = providerPayload(form, editingProvider);
    try {
      await props.onSaveProvider(payload, editingId || undefined);
      closeDialog();
    } catch {
      // The parent surfaces the operation message; keep the current form for correction.
    }
  }

  function openCreateDialog() {
    setEditingId('');
    setForm(emptyForm);
    setDialogOpen(true);
  }

  function editProvider(provider: CatalogProvider) {
    setEditingId(provider.id);
    setForm({
      code: provider.code,
      displayName: provider.displayName,
      providerType: provider.providerType,
      iconPath: provider.iconPath ?? '',
      defaultBaseUrl: provider.defaultBaseUrl ?? '',
      defaultAuthType: provider.defaultAuthType ?? 'APIKey',
      source: provider.source ?? 'gateway',
      status: provider.status,
    });
    setDialogOpen(true);
  }

  function closeDialog() {
    setEditingId('');
    setForm(emptyForm);
    setDialogOpen(false);
  }

  async function deleteProvider(provider: CatalogProvider) {
    try {
      await props.onDeleteProvider(provider.id);
      setPendingDeleteProvider(null);
      if (editingId === provider.id) {
        closeDialog();
      }
    } catch {
      // The parent surfaces the operation message.
    }
  }

  return (
    <div className="pageStack">
      <Card>
        <CardHeader>
          <CardTitle>模型厂商</CardTitle>
          <Badge variant="secondary">{props.providers.length}</Badge>
        </CardHeader>
        <CardContent>
          <div className="providerToolbar">
            <p>默认数据来自原 server-main integration-platform，包含厂商名称、code、图标、Base URL 和授权类型。</p>
            <Button type="button" onClick={openCreateDialog}>
              <Plus size={15} />
              新增厂商
            </Button>
          </div>
          {props.message && <p className="formMessage">{props.message}</p>}
        </CardContent>
      </Card>

      <section className="providerCatalogGrid">
        {props.providers.map((provider) => (
          <article className="providerCatalogCard" key={provider.id}>
            <ProviderLogo provider={provider} />
            <div className="providerCatalogBody">
              <div>
                <strong>{provider.displayName}</strong>
                <span>Code: {provider.code}</span>
              </div>
              <div className="providerCatalogMeta">
                <Badge variant={provider.status === 'active' ? 'success' : 'secondary'}>{provider.status}</Badge>
                <span>spec_type: {provider.providerType}</span>
                <span>{provider.defaultAuthType ?? 'APIKey'}</span>
                {provider.defaultBaseUrl && <span>{provider.defaultBaseUrl}</span>}
                <span>{provider.source ?? 'gateway'}</span>
              </div>
            </div>
            <div className="providerCatalogActions">
              <Button type="button" variant="outline" size="sm" onClick={() => editProvider(provider)}>
                <Pencil size={14} />
                修改
              </Button>
              <Button type="button" variant="destructive" size="sm" onClick={() => setPendingDeleteProvider(provider)}>
                <Trash2 size={14} />
                删除
              </Button>
            </div>
          </article>
        ))}
        {!props.providers.length && (
          <Card>
            <CardContent className="emptyState">
              <strong>暂无模型厂商</strong>
            </CardContent>
          </Card>
        )}
      </section>

      <FormDialog
        ariaLabel={editingId ? '编辑模型厂商' : '新增模型厂商'}
        eyebrow={editingId ? 'Edit Provider' : 'New Provider'}
        footer={(
          <>
            <Button type="submit" disabled={props.state === 'loading'}>
              {editingId ? <Pencil size={15} /> : <Plus size={15} />}
              {editingId ? '保存修改' : '新增厂商'}
            </Button>
            <Button type="button" variant="outline" onClick={closeDialog}>
              <RotateCcw size={15} />
              取消
            </Button>
          </>
        )}
        open={dialogOpen}
        title={editingId ? '编辑模型厂商' : '新增模型厂商'}
        onClose={closeDialog}
        onSubmit={submit}
      >
        <Label>
          Code
          <Input value={form.code} onChange={(event) => setForm({ ...form, code: event.target.value })} placeholder="integration-platform code" />
        </Label>
        <Label>
          名称
          <Input value={form.displayName} onChange={(event) => setForm({ ...form, displayName: event.target.value })} placeholder="OpenAI" />
        </Label>
        <Label>
          类型 spec_type
          <Select value={form.providerType} onChange={(event) => setForm({ ...form, providerType: event.target.value })}>
            {specTypes.map((item) => <option value={item} key={item}>{item}</option>)}
          </Select>
        </Label>
        <Label className="spanTwo">
          图标 URL
          <Input value={form.iconPath} onChange={(event) => setForm({ ...form, iconPath: event.target.value })} placeholder="https://static.51easyai.com/xxx.png" />
        </Label>
        <Label className="spanTwo">
          默认 Base URL
          <Input value={form.defaultBaseUrl} onChange={(event) => setForm({ ...form, defaultBaseUrl: event.target.value })} placeholder="https://api.example.com/v1" />
        </Label>
        <Label>
          默认授权类型
          <Select value={form.defaultAuthType} onChange={(event) => setForm({ ...form, defaultAuthType: event.target.value })}>
            {authTypeOptions.map((item) => <option value={item} key={item}>{item}</option>)}
          </Select>
        </Label>
        <Label>
          来源
          <Input value={form.source} onChange={(event) => setForm({ ...form, source: event.target.value })} />
        </Label>
        <Label>
          状态
          <Select value={form.status} onChange={(event) => setForm({ ...form, status: event.target.value })}>
            {providerStatuses.map((item) => <option value={item} key={item}>{item}</option>)}
          </Select>
        </Label>
      </FormDialog>
      <ConfirmDialog
        confirmLabel="删除厂商"
        description="删除模型厂商后不可恢复，请确认没有仍需保留的模型目录数据。"
        loading={props.state === 'loading'}
        open={Boolean(pendingDeleteProvider)}
        title={`确认删除模型厂商 ${pendingDeleteProvider?.displayName ?? ''}？`}
        onCancel={() => setPendingDeleteProvider(null)}
        onConfirm={() => pendingDeleteProvider ? deleteProvider(pendingDeleteProvider) : undefined}
      />
    </div>
  );
}

function ProviderLogo(props: { provider: CatalogProvider }) {
  if (props.provider.iconPath) {
    return (
      <div className="providerCatalogLogo">
        <img src={props.provider.iconPath} alt="" />
      </div>
    );
  }
  return <div className="providerCatalogLogo">{providerInitials(props.provider.displayName)}</div>;
}

function providerPayload(form: ProviderForm, current?: CatalogProvider): CatalogProviderUpsertRequest {
  const code = form.code.trim();
  return {
    providerKey: current?.providerKey ?? code,
    code,
    displayName: form.displayName.trim(),
    providerType: form.providerType.trim() || 'openai',
    iconPath: form.iconPath.trim(),
    defaultBaseUrl: form.defaultBaseUrl.trim(),
    defaultAuthType: form.defaultAuthType.trim() || 'APIKey',
    source: form.source.trim() || 'gateway',
    status: form.status,
    capabilitySchema: current?.capabilitySchema ?? {},
    defaultRateLimitPolicy: current?.defaultRateLimitPolicy ?? {},
    metadata: current?.metadata ?? {},
  };
}

function providerInitials(label: string) {
  return label
    .split(/\s+/)
    .map((part) => part[0])
    .join('')
    .slice(0, 2)
    .toUpperCase() || 'AI';
}
