'use client';

import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { apiFetch, type Goal, type GoalStatus } from '../../../lib/api';
import { useSession } from '../../../components/session-provider';

const GOAL_STATUS_LABELS: Record<GoalStatus, string> = {
  not_started: 'Neînceput',
  on_track: 'Pe track',
  at_risk: 'La risc',
  achieved: 'Atins',
  abandoned: 'Abandonat',
};

const STATUS_COLORS: Record<GoalStatus, string> = {
  not_started: 'text-ink-faint',
  on_track: 'text-signal-ok',
  at_risk: 'text-signal-warn',
  achieved: 'text-bronze-deep',
  abandoned: 'text-ink-line',
};

const createGoalSchema = z.object({
  horizon: z.string().min(1, 'Orizontul este obligatoriu').max(500),
  metric: z.string().min(1, 'Metrica este obligatorie').max(500),
  target: z.string().min(1, 'Ținta este obligatorie').max(1000),
});
type CreateGoalForm = z.infer<typeof createGoalSchema>;

export default function GoalsPage() {
  const { activeTenant } = useSession();
  const tenantId = activeTenant?.tenantId ?? '';
  const queryClient = useQueryClient();
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [statusFilter, setStatusFilter] = useState<GoalStatus | ''>('');

  const { data: goals = [], isLoading } = useQuery({
    queryKey: ['goals', tenantId, statusFilter],
    queryFn: () =>
      apiFetch<Goal[]>(
        `/v1/goals${statusFilter ? `?status=${statusFilter}` : ''}`,
        { tenantId },
      ),
    enabled: Boolean(tenantId),
  });

  const { register, handleSubmit, reset, formState: { errors, isSubmitting } } = useForm<CreateGoalForm>({
    resolver: zodResolver(createGoalSchema),
  });

  const createGoal = useMutation({
    mutationFn: (values: CreateGoalForm) =>
      apiFetch<Goal>('/v1/goals', { method: 'POST', tenantId, body: values }),
    onSuccess: async () => {
      await queryClient.invalidateQueries({ queryKey: ['goals', tenantId] });
      reset();
      setIsFormOpen(false);
    },
  });

  const updateStatus = useMutation({
    mutationFn: ({ id, status }: { id: string; status: GoalStatus }) =>
      apiFetch<Goal>(`/v1/goals/${id}`, { method: 'PATCH', tenantId, body: { status } }),
    onSuccess: async () => {
      await queryClient.invalidateQueries({ queryKey: ['goals', tenantId] });
    },
  });

  const deleteGoal = useMutation({
    mutationFn: (id: string) =>
      apiFetch<{ deleted: boolean }>(`/v1/goals/${id}`, { method: 'DELETE', tenantId }),
    onSuccess: async () => {
      await queryClient.invalidateQueries({ queryKey: ['goals', tenantId] });
    },
  });

  return (
    <div className="max-w-3xl">
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="font-display text-2xl font-semibold text-ink">Obiective</h1>
          <p className="text-sm text-ink-faint">Obiectivele strategice urmărite în acest workspace.</p>
        </div>
        <button type="button" className="btn-primary" onClick={() => setIsFormOpen((v) => !v)}>
          {isFormOpen ? 'Anulează' : 'Obiectiv nou'}
        </button>
      </div>

      {isFormOpen && (
        <form
          onSubmit={handleSubmit((values) => createGoal.mutate(values))}
          noValidate
          className="card mb-6 space-y-4 p-5"
        >
          <div>
            <label className="label" htmlFor="goal-horizon">Orizont</label>
            <input
              id="goal-horizon"
              type="text"
              className="field"
              placeholder="ex: Q3 2026, 12 luni, Trimestrul II"
              {...register('horizon')}
            />
            {errors.horizon && <p className="mt-1 text-xs text-signal-danger">{errors.horizon.message}</p>}
          </div>
          <div>
            <label className="label" htmlFor="goal-metric">Metrică</label>
            <input
              id="goal-metric"
              type="text"
              className="field"
              placeholder="ex: Cifra de afaceri, Clienți noi, Uptime"
              {...register('metric')}
            />
            {errors.metric && <p className="mt-1 text-xs text-signal-danger">{errors.metric.message}</p>}
          </div>
          <div>
            <label className="label" htmlFor="goal-target">Țintă</label>
            <input
              id="goal-target"
              type="text"
              className="field"
              placeholder="ex: 500.000 EUR, 50 clienți, 99.9%"
              {...register('target')}
            />
            {errors.target && <p className="mt-1 text-xs text-signal-danger">{errors.target.message}</p>}
          </div>
          {createGoal.isError && (
            <p className="text-sm text-signal-danger">
              {createGoal.error instanceof Error ? createGoal.error.message : 'Eroare la creare'}
            </p>
          )}
          <button type="submit" disabled={isSubmitting || createGoal.isPending} className="btn-primary">
            Salvează
          </button>
        </form>
      )}

      <div className="mb-4 flex flex-wrap gap-2">
        <button
          type="button"
          onClick={() => setStatusFilter('')}
          className={`rounded-full px-3 py-1 text-xs font-medium transition-colors ${
            statusFilter === '' ? 'bg-ink text-paper' : 'bg-paper-sunken text-ink-soft hover:text-ink'
          }`}
        >
          Toate
        </button>
        {(Object.keys(GOAL_STATUS_LABELS) as GoalStatus[]).map((status) => (
          <button
            key={status}
            type="button"
            onClick={() => setStatusFilter(status)}
            className={`rounded-full px-3 py-1 text-xs font-medium transition-colors ${
              statusFilter === status ? 'bg-ink text-paper' : 'bg-paper-sunken text-ink-soft hover:text-ink'
            }`}
          >
            {GOAL_STATUS_LABELS[status]}
          </button>
        ))}
      </div>

      {isLoading && <p className="text-sm text-ink-faint">Se încarcă…</p>}
      {!isLoading && goals.length === 0 && (
        <p className="card p-6 text-sm text-ink-faint">
          {statusFilter
            ? `Niciun obiectiv cu statusul "${GOAL_STATUS_LABELS[statusFilter]}".`
            : 'Niciun obiectiv încă. Adaugă primul mai sus.'}
        </p>
      )}

      <ul className="space-y-3">
        {goals.map((goal) => (
          <li key={goal.id} className="card p-4">
            <div className="flex items-start justify-between gap-4">
              <div className="flex-1 min-w-0">
                <p className="text-[11px] font-medium uppercase tracking-wider text-ink-faint">{goal.horizon}</p>
                <p className="mt-0.5 text-sm font-medium text-ink truncate">{goal.metric}</p>
                <p className="mt-0.5 text-sm text-ink-soft">{goal.target}</p>
              </div>
              <div className="flex items-center gap-2 shrink-0">
                <select
                  aria-label={`Status pentru ${goal.metric}`}
                  className={`rounded-lg border border-ink-line bg-paper-raised px-2.5 py-1.5 text-xs font-medium
                    focus:border-bronze focus:outline-none focus:ring-2 focus:ring-bronze/20
                    ${STATUS_COLORS[goal.status]}`}
                  value={goal.status}
                  onChange={(e) =>
                    updateStatus.mutate({ id: goal.id, status: e.target.value as GoalStatus })
                  }
                >
                  {(Object.entries(GOAL_STATUS_LABELS) as [GoalStatus, string][]).map(([value, label]) => (
                    <option key={value} value={value}>{label}</option>
                  ))}
                </select>
                <button
                  type="button"
                  onClick={() => deleteGoal.mutate(goal.id)}
                  disabled={deleteGoal.isPending}
                  className="text-xs text-signal-danger hover:underline disabled:opacity-50"
                >
                  Șterge
                </button>
              </div>
            </div>
          </li>
        ))}
      </ul>
    </div>
  );
}
