"use client";

import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Plus, TrendingUp, TrendingDown, DollarSign, Download } from "lucide-react";
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid,
  Tooltip, ResponsiveContainer, Legend,
} from "recharts";
import { transactionsApi } from "@/lib/api";
import { Transaction } from "@/types";
import { PageHeader, Modal, StatCard, EmptyState, Spinner, ConfirmDialog } from "@/components/ui";
import { formatCurrency, formatDate } from "@/lib/utils";
import { useForm } from "react-hook-form";
import toast from "react-hot-toast";

const MONTHS = ["Oca", "Şub", "Mar", "Nis", "May", "Haz", "Tem", "Ağu", "Eyl", "Eki", "Kas", "Ara"];
const CATEGORIES = ["Yazılım", "Pazarlama", "Ofis", "Ulaşım", "Yemek", "Eğitim", "Sağlık", "Diğer"];

function TransactionForm({ transaction, onClose }: { transaction?: Transaction; onClose: () => void }) {
  const qc = useQueryClient();
  const { register, handleSubmit, watch, formState: { errors } } = useForm({
    defaultValues: transaction ? {
      date: transaction.date,
      description: transaction.description,
      category: transaction.category || "",
      amount: parseFloat(transaction.amount),
      type: transaction.type,
    } : { type: "gelir", date: new Date().toISOString().split("T")[0] },
  });

  const txType = watch("type");

  const mutation = useMutation({
    mutationFn: (data: Record<string, unknown>) =>
      transaction ? transactionsApi.update(transaction.id, data) : transactionsApi.create(data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["transactions"] });
      qc.invalidateQueries({ queryKey: ["finance-summary"] });
      qc.invalidateQueries({ queryKey: ["dashboard-stats"] });
      toast.success(transaction ? "İşlem güncellendi." : "İşlem eklendi.");
      onClose();
    },
    onError: () => toast.error("Bir hata oluştu."),
  });

  return (
    <form onSubmit={handleSubmit((d) => mutation.mutate(d))} className="space-y-4">
      <div>
        <label className="form-label">İşlem Türü</label>
        <div className="flex gap-2">
          {[
            { value: "gelir", label: "💰 Gelir", cls: "border-green-500/50 text-green-400 bg-green-500/10" },
            { value: "gider", label: "💸 Gider", cls: "border-red-500/50 text-red-400 bg-red-500/10" },
          ].map(({ value, label, cls }) => (
            <label key={value} className={`flex-1 flex items-center justify-center gap-2 p-2.5 rounded-lg border cursor-pointer text-sm font-medium transition-all ${txType === value ? cls : "border-surface-500 text-surface-500 hover:border-surface-400"}`}>
              <input {...register("type")} type="radio" value={value} className="sr-only" />
              {label}
            </label>
          ))}
        </div>
      </div>
      <div className="grid grid-cols-2 gap-3">
        <div>
          <label className="form-label">Tarih</label>
          <input {...register("date", { required: true })} type="date" className="kaplan-input" />
        </div>
        <div>
          <label className="form-label">Tutar (₺) *</label>
          <input {...register("amount", { required: true, min: 0.01, valueAsNumber: true })} type="number" step="0.01" placeholder="0.00" className="kaplan-input" />
        </div>
      </div>
      <div>
        <label className="form-label">Açıklama *</label>
        <input {...register("description", { required: "Açıklama zorunlu." })} className="kaplan-input" placeholder="İşlem açıklaması" />
        {errors.description && <p className="text-xs text-red-400 mt-1">{errors.description.message as string}</p>}
      </div>
      <div>
        <label className="form-label">Kategori</label>
        <select {...register("category")} className="kaplan-select">
          <option value="">Kategori seç</option>
          {CATEGORIES.map((c) => <option key={c} value={c}>{c}</option>)}
        </select>
      </div>
      <div className="flex gap-3 justify-end pt-2">
        <button type="button" onClick={onClose} className="btn-secondary">İptal</button>
        <button type="submit" disabled={mutation.isPending} className="btn-primary">
          {mutation.isPending && <Spinner size={14} />}
          {transaction ? "Güncelle" : "Ekle"}
        </button>
      </div>
    </form>
  );
}

export default function FinansPage() {
  const qc = useQueryClient();
  const year = new Date().getFullYear();
  const month = new Date().getMonth() + 1;

  const [modal, setModal] = useState<{ open: boolean; tx?: Transaction }>({ open: false });
  const [deleteModal, setDeleteModal] = useState<{ open: boolean; txId?: number }>({ open: false });
  const [filterType, setFilterType] = useState("");

  const { data: transactions = [], isLoading } = useQuery<Transaction[]>({
    queryKey: ["transactions", filterType],
    queryFn: () => transactionsApi.list(filterType ? { type: filterType } : {}),
  });

  const { data: summary } = useQuery({
    queryKey: ["finance-summary", year, month],
    queryFn: () => transactionsApi.getSummary({ year, month }),
  });

  // Yıllık grafik verisi
  const { data: yearlyData } = useQuery({
    queryKey: ["yearly-chart", year],
    queryFn: async () => {
      return Promise.all(
        MONTHS.map(async (name, i) => {
          const s = await transactionsApi.getSummary({ year, month: i + 1 });
          return {
            name,
            Gelir: parseFloat(s.total_income || "0"),
            Gider: parseFloat(s.total_expense || "0"),
          };
        })
      );
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (id: number) => transactionsApi.delete(id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["transactions"] });
      qc.invalidateQueries({ queryKey: ["finance-summary"] });
      toast.success("İşlem silindi.");
      setDeleteModal({ open: false });
    },
  });

  const income = parseFloat(summary?.total_income || "0");
  const expense = parseFloat(summary?.total_expense || "0");
  const profit = income - expense;

  return (
    <div className="space-y-5 animate-fade-in">
      <PageHeader
        title="Gelir / Gider Takibi"
        subtitle="Finansal performansınızı takip edin"
        action={
          <button onClick={() => setModal({ open: true })} className="btn-primary">
            <Plus size={16} /> Yeni İşlem
          </button>
        }
      />

      {/* Özet Kartları */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <StatCard title="Bu Ay Gelir" value={formatCurrency(income)} icon={<TrendingUp />} color="green" subtitle={`${year} / ${month}. Ay`} />
        <StatCard title="Bu Ay Gider" value={formatCurrency(expense)} icon={<TrendingDown />} color="red" />
        <StatCard title="Net Kâr" value={formatCurrency(profit)} icon={<DollarSign />} color={profit >= 0 ? "blue" : "red"} />
      </div>

      {/* Yıllık Grafik */}
      <div className="kaplan-card">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h3 className="text-sm font-semibold text-surface-100">{year} Yıllık Gelir/Gider Grafiği</h3>
            <p className="text-xs text-surface-500">Aylık kırılım</p>
          </div>
          <button className="btn-ghost text-xs gap-1.5">
            <Download size={13} /> PDF İndir
          </button>
        </div>
        <ResponsiveContainer width="100%" height={220}>
          <BarChart data={yearlyData || []}>
            <CartesianGrid strokeDasharray="3 3" stroke="#3a3a42" vertical={false} />
            <XAxis dataKey="name" tick={{ fill: "#8b8b98", fontSize: 11 }} axisLine={false} tickLine={false} />
            <YAxis tick={{ fill: "#8b8b98", fontSize: 11 }} axisLine={false} tickLine={false} tickFormatter={(v) => `₺${(v / 1000).toFixed(0)}K`} />
            <Tooltip
              contentStyle={{ background: "#242428", border: "1px solid #3a3a42", borderRadius: "8px", fontSize: "12px" }}
              formatter={(v: number) => [formatCurrency(v), ""]}
            />
            <Legend iconType="circle" iconSize={8} wrapperStyle={{ fontSize: "12px", color: "#8b8b98" }} />
            <Bar dataKey="Gelir" fill="#22c55e" radius={[4, 4, 0, 0]} maxBarSize={32} />
            <Bar dataKey="Gider" fill="#ef4444" radius={[4, 4, 0, 0]} maxBarSize={32} />
          </BarChart>
        </ResponsiveContainer>
      </div>

      {/* İşlem Tablosu */}
      <div className="kaplan-card overflow-hidden p-0">
        <div className="flex items-center justify-between px-5 py-3 border-b border-surface-500">
          <h3 className="text-sm font-semibold text-surface-100">İşlemler</h3>
          <div className="flex gap-2">
            {[{ v: "", l: "Tümü" }, { v: "gelir", l: "Gelirler" }, { v: "gider", l: "Giderler" }].map(({ v, l }) => (
              <button key={v} onClick={() => setFilterType(v)}
                className={`text-xs px-3 py-1.5 rounded-lg transition-colors ${filterType === v ? "bg-brand-600 text-white" : "text-surface-400 hover:text-surface-200 hover:bg-surface-600"}`}>
                {l}
              </button>
            ))}
          </div>
        </div>
        {isLoading ? (
          <div className="flex justify-center py-12"><Spinner /></div>
        ) : transactions.length === 0 ? (
          <EmptyState icon="💰" title="İşlem bulunamadı" description="Yeni gelir veya gider kaydı ekleyin." action={<button onClick={() => setModal({ open: true })} className="btn-primary"><Plus size={14} /> İşlem Ekle</button>} />
        ) : (
          <table className="kaplan-table">
            <thead>
              <tr>
                <th>Tarih</th>
                <th>Açıklama</th>
                <th>Kategori</th>
                <th>Tür</th>
                <th className="text-right">Tutar</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {transactions.map((tx) => (
                <tr key={tx.id}>
                  <td className="text-surface-400 text-sm">{formatDate(tx.date)}</td>
                  <td className="max-w-xs truncate">{tx.description}</td>
                  <td className="text-surface-500 text-sm">{tx.category || "—"}</td>
                  <td>
                    <span className={`badge text-xs ${tx.type === "gelir" ? "badge-green" : "badge-red"}`}>
                      {tx.type === "gelir" ? "Gelir" : "Gider"}
                    </span>
                  </td>
                  <td className={`text-right font-semibold ${tx.type === "gelir" ? "text-green-400" : "text-red-400"}`}>
                    {tx.type === "gelir" ? "+" : "-"}{formatCurrency(parseFloat(tx.amount))}
                  </td>
                  <td>
                    <div className="flex gap-1 justify-end">
                      <button onClick={() => setModal({ open: true, tx })} className="btn-ghost text-xs px-2 py-1">Düzenle</button>
                      <button onClick={() => setDeleteModal({ open: true, txId: tx.id })} className="btn-ghost text-xs px-2 py-1 text-red-400">Sil</button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      <Modal open={modal.open} onClose={() => setModal({ open: false })} title={modal.tx ? "İşlemi Düzenle" : "Yeni İşlem Ekle"}>
        <TransactionForm transaction={modal.tx} onClose={() => setModal({ open: false })} />
      </Modal>

      <ConfirmDialog
        open={deleteModal.open}
        onClose={() => setDeleteModal({ open: false })}
        onConfirm={() => deleteModal.txId && deleteMutation.mutate(deleteModal.txId)}
        title="İşlemi Sil"
        description="Bu işlemi silmek istediğinizden emin misiniz?"
        loading={deleteMutation.isPending}
      />
    </div>
  );
}
