"use client";
import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Plus } from "lucide-react";
import { goalsApi } from "@/lib/api";
import { Goal } from "@/types";
import { PageHeader, Modal, ProgressBar, StatusBadge, EmptyState, Spinner } from "@/components/ui";
import { formatDate, progressColor } from "@/lib/utils";
import { useForm } from "react-hook-form";
import toast from "react-hot-toast";

function GoalForm({ goal, onClose }: { goal?: Goal; onClose: () => void }) {
  const qc = useQueryClient();
  const { register, handleSubmit } = useForm({ defaultValues: goal ? { title: goal.title, description: goal.description || "", target_value: parseFloat(goal.target_value), unit: goal.unit || "", due_date: goal.due_date || "", category: goal.category || "" } : {} });
  const mutation = useMutation({ mutationFn: (data: Record<string, unknown>) => goal ? goalsApi.update(goal.id, data) : goalsApi.create(data), onSuccess: () => { qc.invalidateQueries({ queryKey: ["goals"] }); toast.success(goal ? "Hedef güncellendi." : "Hedef oluşturuldu."); onClose(); } });
  return (
    <form onSubmit={handleSubmit((d) => mutation.mutate({ ...d, target_value: parseFloat(d.target_value as string) }))} className="space-y-4">
      <div><label className="form-label">Hedef Başlığı *</label><input {...register("title", { required: true })} className="kaplan-input" placeholder="ör: Aylık 50.000 TL gelir" /></div>
      <div><label className="form-label">Açıklama</label><textarea {...register("description")} rows={2} className="kaplan-textarea" /></div>
      <div className="grid grid-cols-2 gap-3"><div><label className="form-label">Hedef Değer *</label><input {...register("target_value", { required: true })} type="number" step="0.01" className="kaplan-input" /></div><div><label className="form-label">Birim</label><input {...register("unit")} className="kaplan-input" placeholder="ör: TL, müşteri, saat" /></div></div>
      <div className="grid grid-cols-2 gap-3"><div><label className="form-label">Kategori</label><input {...register("category")} className="kaplan-input" /></div><div><label className="form-label">Son Tarih</label><input {...register("due_date")} type="date" className="kaplan-input" /></div></div>
      <div className="flex gap-3 justify-end"><button type="button" onClick={onClose} className="btn-secondary">İptal</button><button type="submit" disabled={mutation.isPending} className="btn-primary">{mutation.isPending && <Spinner size={14} />}{goal ? "Güncelle" : "Oluştur"}</button></div>
    </form>
  );
}

export default function HedeflerPage() {
  const qc = useQueryClient();
  const [modal, setModal] = useState<{ open: boolean; goal?: Goal }>({ open: false });
  const [progressModal, setProgressModal] = useState<{ open: boolean; goal?: Goal }>({ open: false });
  const [progressValue, setProgressValue] = useState("");
  const { data: goals = [], isLoading } = useQuery<Goal[]>({ queryKey: ["goals"], queryFn: () => goalsApi.list() });
  const progressMutation = useMutation({ mutationFn: ({ id, value }: { id: number; value: number }) => goalsApi.updateProgress(id, value), onSuccess: () => { qc.invalidateQueries({ queryKey: ["goals"] }); toast.success("İlerleme güncellendi."); setProgressModal({ open: false }); } });

  const active = goals.filter((g) => g.status === "aktif");
  const done = goals.filter((g) => g.status !== "aktif");

  return (
    <div className="space-y-5 animate-fade-in">
      <PageHeader title="Hedef Takibi" subtitle={`${active.length} aktif hedef`} action={<button onClick={() => setModal({ open: true })} className="btn-primary"><Plus size={16} /> Yeni Hedef</button>} />
      {isLoading ? <div className="flex justify-center py-12"><Spinner /></div> : goals.length === 0 ? <EmptyState icon="🎯" title="Henüz hedef yok" description="İlk hedefinizi belirleyin." action={<button onClick={() => setModal({ open: true })} className="btn-primary"><Plus size={14} /> Hedef Ekle</button>} /> : (
        <>
          {active.length > 0 && (<div><h3 className="text-sm font-semibold text-surface-400 mb-3">Aktif Hedefler</h3><div className="grid grid-cols-1 md:grid-cols-2 gap-4">{active.map((g) => (<div key={g.id} className="kaplan-card space-y-3"><div className="flex items-start justify-between"><div><h4 className="font-semibold text-surface-100">{g.title}</h4>{g.category && <span className="text-xs text-surface-500">{g.category}</span>}</div><StatusBadge status={g.status} /></div>{g.description && <p className="text-sm text-surface-500">{g.description}</p>}<div className="space-y-1.5"><div className="flex justify-between text-xs text-surface-400"><span>{parseFloat(g.current_value).toLocaleString("tr")} / {parseFloat(g.target_value).toLocaleString("tr")} {g.unit}</span><span className="font-medium text-surface-300">{g.progress_pct}%</span></div><ProgressBar value={g.progress_pct} /></div>{g.due_date && <p className="text-xs text-surface-500">Son tarih: {formatDate(g.due_date)}</p>}<div className="flex gap-2"><button onClick={() => { setProgressModal({ open: true, goal: g }); setProgressValue(g.current_value); }} className="btn-secondary text-xs flex-1 justify-center">İlerleme Güncelle</button><button onClick={() => setModal({ open: true, goal: g })} className="btn-ghost text-xs px-2">✏️</button></div></div>))}</div></div>)}
          {done.length > 0 && (<div><h3 className="text-sm font-semibold text-surface-400 mb-3">Tamamlanan / İptal</h3><div className="grid grid-cols-1 md:grid-cols-2 gap-4">{done.map((g) => (<div key={g.id} className="kaplan-card opacity-60 space-y-2"><div className="flex items-center justify-between"><h4 className="font-medium text-surface-200">{g.title}</h4><StatusBadge status={g.status} /></div><ProgressBar value={g.progress_pct} /></div>))}</div></div>)}
        </>
      )}
      <Modal open={modal.open} onClose={() => setModal({ open: false })} title={modal.goal ? "Hedefi Düzenle" : "Yeni Hedef"}><GoalForm goal={modal.goal} onClose={() => setModal({ open: false })} /></Modal>
      <Modal open={progressModal.open} onClose={() => setProgressModal({ open: false })} title="İlerleme Güncelle" size="sm">
        <div className="space-y-4">
          <div><label className="form-label">Mevcut Değer ({progressModal.goal?.unit || ""})</label><input type="number" step="0.01" value={progressValue} onChange={(e) => setProgressValue(e.target.value)} className="kaplan-input" /><p className="text-xs text-surface-500 mt-1">Hedef: {progressModal.goal && parseFloat(progressModal.goal.target_value).toLocaleString("tr")} {progressModal.goal?.unit}</p></div>
          <div className="flex gap-3 justify-end"><button onClick={() => setProgressModal({ open: false })} className="btn-secondary">İptal</button><button onClick={() => progressModal.goal && progressMutation.mutate({ id: progressModal.goal.id, value: parseFloat(progressValue) })} disabled={progressMutation.isPending} className="btn-primary">{progressMutation.isPending && <Spinner size={14} />}Kaydet</button></div>
        </div>
      </Modal>
    </div>
  );
}
