import { useState, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Plus } from 'lucide-react';
import { trpc } from '@/lib/trpc';
import { useNotify } from '@/hooks/useNotify';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';

const NO_CLIENT = '__no_client__';

interface InlineProjectFormProps {
  onCancel: () => void;
  onCreated: (projectId: string) => void;
}

export function InlineProjectForm({ onCancel, onCreated }: InlineProjectFormProps) {
  const { t } = useTranslation();
  const { notify, notifyError } = useNotify();

  const [newProjectName, setNewProjectName] = useState('');
  const [newProjectClientId, setNewProjectClientId] = useState(NO_CLIENT);
  const [newProjectSubClientId, setNewProjectSubClientId] = useState(NO_CLIENT);
  const [creatingClient, setCreatingClient] = useState(false);
  const [newClientName, setNewClientName] = useState('');
  const [creatingSubClient, setCreatingSubClient] = useState(false);
  const [newSubClientName, setNewSubClientName] = useState('');

  const { data: clientList = [] } = trpc.clients.list.useQuery();
  const utils = trpc.useUtils();

  const topLevelClients = useMemo(() => clientList.filter((c) => !c.parentId), [clientList]);
  const subClientsByParent = useMemo(() => {
    const m = new Map<string, typeof clientList>();
    for (const c of clientList) {
      if (c.parentId) {
        const arr = m.get(c.parentId) ?? [];
        arr.push(c);
        m.set(c.parentId, arr);
      }
    }
    return m;
  }, [clientList]);

  const createClientMutation = trpc.clients.create.useMutation({
    onSuccess: () => {
      notify('success', 'toast.client.created');
      void utils.clients.list.invalidate();
    },
  });
  const createProjectMutation = trpc.projects.create.useMutation({
    onSuccess: () => void utils.projects.listAll.invalidate(),
  });

  const isSubmitting = createClientMutation.isPending || createProjectMutation.isPending;

  async function handleCreate() {
    if (!newProjectName.trim()) return;
    try {
      let resolvedClientId: string | undefined;

      if (creatingClient && newClientName.trim()) {
        const r = await createClientMutation.mutateAsync({ name: newClientName.trim() });
        resolvedClientId = r.id;
        if (creatingSubClient && newSubClientName.trim()) {
          const sr = await createClientMutation.mutateAsync({
            name: newSubClientName.trim(),
            parentId: resolvedClientId,
          });
          resolvedClientId = sr.id;
        }
      } else if (newProjectClientId !== NO_CLIENT) {
        if (creatingSubClient && newSubClientName.trim()) {
          const sr = await createClientMutation.mutateAsync({
            name: newSubClientName.trim(),
            parentId: newProjectClientId,
          });
          resolvedClientId = sr.id;
        } else if (newProjectSubClientId !== NO_CLIENT) {
          resolvedClientId = newProjectSubClientId;
        } else {
          resolvedClientId = newProjectClientId;
        }
      }

      const r = await createProjectMutation.mutateAsync({
        name: newProjectName.trim(),
        clientId: resolvedClientId,
      });
      onCreated(r.id);
    } catch (err) {
      notifyError('toast.project.createError', err as Error);
    }
  }

  return (
    <div className="flex flex-col gap-3 p-2">
      <div className="flex items-center justify-between">
        <span className="text-sm font-medium">{t('projects.newProject')}</span>
        <Button type="button" variant="ghost" size="sm" onClick={onCancel}>
          {t('common.cancel')}
        </Button>
      </div>

      {/* Project name */}
      <Input
        placeholder={t('projects.projectNamePlaceholder')}
        value={newProjectName}
        onChange={(e) => setNewProjectName(e.target.value)}
        autoFocus
        className="h-8 text-sm"
      />

      {/* Client selection */}
      <div className="flex flex-col gap-1.5">
        <label className="text-xs text-muted-foreground">
          {t('projects.clientOptional')} <span className="opacity-60">{t('projects.clientOptionalHint')}</span>
        </label>
        {creatingClient ? (
          <div className="flex items-center gap-1.5">
            <Input
              placeholder={t('projects.newClientName')}
              value={newClientName}
              onChange={(e) => setNewClientName(e.target.value)}
              className="flex-1 h-8 text-sm"
            />
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={() => {
                setCreatingClient(false);
                setNewClientName('');
                setCreatingSubClient(false);
                setNewSubClientName('');
              }}
            >
              {t('common.cancel')}
            </Button>
          </div>
        ) : (
          <div className="flex items-center gap-1.5">
            <Select
              value={newProjectClientId}
              onValueChange={(v) => {
                setNewProjectClientId(v);
                setNewProjectSubClientId(NO_CLIENT);
                setCreatingSubClient(false);
                setNewSubClientName('');
              }}
            >
              <SelectTrigger className="flex-1 h-8 text-sm">
                <SelectValue placeholder={t('projects.selectClient')} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={NO_CLIENT}>{t('projects.noneInternal')}</SelectItem>
                {topLevelClients.map((c) => (
                  <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={() => setCreatingClient(true)}
            >
              <Plus className="size-3.5 mr-1" />{t('projects.new')}
            </Button>
          </div>
        )}
      </div>

      {/* Sub-client selection */}
      {(newProjectClientId !== NO_CLIENT || (creatingClient && newClientName.trim())) && (
        <div className="flex flex-col gap-1.5">
          <label className="text-xs text-muted-foreground">
            {t('projects.subClientOptional')} <span className="opacity-60">{t('projects.clientOptionalHint')}</span>
          </label>
          {creatingSubClient ? (
            <div className="flex items-center gap-1.5">
              <Input
                placeholder={t('projects.newSubClientName')}
                value={newSubClientName}
                onChange={(e) => setNewSubClientName(e.target.value)}
                className="flex-1 h-8 text-sm"
              />
              <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={() => {
                  setCreatingSubClient(false);
                  setNewSubClientName('');
                }}
              >
                {t('common.cancel')}
              </Button>
            </div>
          ) : creatingClient ? (
            <Button
              type="button"
              variant="outline"
              size="sm"
              className="w-fit"
              onClick={() => setCreatingSubClient(true)}
            >
              <Plus className="size-3.5 mr-1" />{t('projects.newSubClient')}
            </Button>
          ) : (
            <div className="flex items-center gap-1.5">
              <Select
                value={newProjectSubClientId}
                onValueChange={setNewProjectSubClientId}
              >
                <SelectTrigger className="flex-1 h-8 text-sm">
                  <SelectValue placeholder={t('projects.selectSubClient')} />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value={NO_CLIENT}>{t('projects.none')}</SelectItem>
                  {(subClientsByParent.get(newProjectClientId) ?? []).map((sc) => (
                    <SelectItem key={sc.id} value={sc.id}>{sc.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => setCreatingSubClient(true)}
              >
                <Plus className="size-3.5 mr-1" />{t('projects.new')}
              </Button>
            </div>
          )}
        </div>
      )}

      <div className="flex justify-end">
        <Button
          type="button"
          size="sm"
          onClick={handleCreate}
          disabled={!newProjectName.trim() || isSubmitting}
        >
          {isSubmitting ? t('common.creating') : t('projects.createProject')}
        </Button>
      </div>
    </div>
  );
}
