import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { userListOptions } from "../lib/queries/users";
import { useAlert } from "../context/AlertContext";
import { useAuth } from "../context/AuthContext";
import Forbidden from "../components/Forbidden";
import { useNavigate, Link } from "react-router-dom";
import { motion } from "framer-motion";

import AdminDatePicker from "../components/AdminDatePicker";
import FormField from "../components/FormField";
import { useApiMutation } from "../lib/queries/mutations";
import { todayLocalStr } from "../utils/formatters";
const API_BASE = "/api/admin";

interface CreateForm {
  user_id: string;
  shift_date: string;
  leave_type: string;
  leave_hours: number;
  arrival_date: string;
  arrival_time: string;
  break_start_date: string;
  break_start_time: string;
  break_end_date: string;
  break_end_time: string;
  departure_date: string;
  departure_time: string;
  notes: string;
}

export default function AttendanceCreate() {
  const alert = useAlert();
  const { hasPermission } = useAuth();
  const navigate = useNavigate();
  const { data: usersData, isPending: loading } = useQuery(userListOptions());
  const users = (usersData ?? []).map((u) => ({
    id: u.id,
    name: `${u.first_name} ${u.last_name}`.trim() || u.username,
  }));
  const [submitting, setSubmitting] = useState(false);

  const createMutation = useApiMutation<CreateForm, { message?: string }>({
    url: () => `${API_BASE}/attendance`,
    method: () => "POST",
    invalidate: ["attendance", "users"],
  });

  const [form, setForm] = useState<CreateForm>(() => {
    const today = todayLocalStr();
    return {
      user_id: "",
      shift_date: today,
      leave_type: "work",
      leave_hours: 8,
      arrival_date: today,
      arrival_time: "",
      break_start_date: today,
      break_start_time: "",
      break_end_date: today,
      break_end_time: "",
      departure_date: today,
      departure_time: "",
      notes: "",
    };
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!form.user_id || !form.shift_date) {
      alert.error("Vyplňte zaměstnance a datum směny");
      return;
    }

    setSubmitting(true);

    try {
      const result = await createMutation.mutateAsync(form);
      alert.success(result?.message || "Uloženo");
      navigate(`/attendance/admin?month=${form.shift_date.substring(0, 7)}`);
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "Chyba připojení");
    } finally {
      setSubmitting(false);
    }
  };

  const handleShiftDateChange = (newDate: string) => {
    setForm({
      ...form,
      shift_date: newDate,
      arrival_date: newDate,
      break_start_date: newDate,
      break_end_date: newDate,
      departure_date: newDate,
    });
  };

  const isWorkType = form.leave_type === "work";

  if (!hasPermission("attendance.manage")) return <Forbidden />;

  if (loading) {
    return (
      <div className="admin-loading">
        <div className="admin-spinner" />
      </div>
    );
  }

  return (
    <div>
      <motion.div
        className="admin-page-header"
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.25 }}
      >
        <div>
          <h1 className="admin-page-title">Přidat záznam docházky</h1>
        </div>
        <div className="admin-page-actions">
          <Link
            to="/attendance/admin"
            className="admin-btn admin-btn-secondary"
          >
            &larr; Zpět na správu
          </Link>
        </div>
      </motion.div>

      <motion.div
        className="admin-card"
        style={{ maxWidth: "600px" }}
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.25, delay: 0.06 }}
      >
        <div className="admin-card-body">
          <form onSubmit={handleSubmit} className="admin-form">
            <div className="admin-form-row">
              <FormField label="Zaměstnanec" required>
                <select
                  value={form.user_id}
                  onChange={(e) =>
                    setForm({ ...form, user_id: e.target.value })
                  }
                  className="admin-form-select"
                  required
                >
                  <option value="">Vyberte zaměstnance</option>
                  {users.map((user) => (
                    <option key={user.id} value={user.id}>
                      {user.name}
                    </option>
                  ))}
                </select>
              </FormField>
              <FormField label="Datum směny" required>
                <AdminDatePicker
                  mode="date"
                  value={form.shift_date}
                  onChange={(val: string) => handleShiftDateChange(val)}
                  required
                />
              </FormField>
            </div>

            <FormField label="Typ záznamu" required>
              <select
                value={form.leave_type}
                onChange={(e) =>
                  setForm({ ...form, leave_type: e.target.value })
                }
                className="admin-form-select"
              >
                <option value="work">Práce</option>
                <option value="vacation">Dovolená</option>
                <option value="sick">Nemoc</option>
                <option value="unpaid">Neplacené volno</option>
              </select>
            </FormField>

            {!isWorkType && (
              <FormField label="Počet hodin">
                <input
                  type="number"
                  value={form.leave_hours}
                  onChange={(e) =>
                    setForm({
                      ...form,
                      leave_hours: parseFloat(e.target.value),
                    })
                  }
                  min="0.5"
                  max="24"
                  step="0.5"
                  className="admin-form-input"
                />
                <small className="admin-form-hint">
                  Výchozí 8 hodin pro celý den
                </small>
              </FormField>
            )}

            {isWorkType && (
              <>
                <div className="admin-form-row">
                  <FormField label="Příchod - datum">
                    <AdminDatePicker
                      mode="date"
                      value={form.arrival_date}
                      onChange={(val: string) =>
                        setForm({ ...form, arrival_date: val })
                      }
                    />
                  </FormField>
                  <FormField label="Příchod - čas">
                    <AdminDatePicker
                      mode="time"
                      value={form.arrival_time}
                      onChange={(val: string) =>
                        setForm({ ...form, arrival_time: val })
                      }
                    />
                  </FormField>
                </div>

                <div className="admin-form-row">
                  <FormField label="Začátek pauzy - datum">
                    <AdminDatePicker
                      mode="date"
                      value={form.break_start_date}
                      onChange={(val: string) =>
                        setForm({ ...form, break_start_date: val })
                      }
                    />
                  </FormField>
                  <FormField label="Začátek pauzy - čas">
                    <AdminDatePicker
                      mode="time"
                      value={form.break_start_time}
                      onChange={(val: string) =>
                        setForm({ ...form, break_start_time: val })
                      }
                    />
                  </FormField>
                </div>

                <div className="admin-form-row">
                  <FormField label="Konec pauzy - datum">
                    <AdminDatePicker
                      mode="date"
                      value={form.break_end_date}
                      onChange={(val: string) =>
                        setForm({ ...form, break_end_date: val })
                      }
                    />
                  </FormField>
                  <FormField label="Konec pauzy - čas">
                    <AdminDatePicker
                      mode="time"
                      value={form.break_end_time}
                      onChange={(val: string) =>
                        setForm({ ...form, break_end_time: val })
                      }
                    />
                  </FormField>
                </div>

                <div className="admin-form-row">
                  <FormField label="Odchod - datum">
                    <AdminDatePicker
                      mode="date"
                      value={form.departure_date}
                      onChange={(val: string) =>
                        setForm({ ...form, departure_date: val })
                      }
                    />
                  </FormField>
                  <FormField label="Odchod - čas">
                    <AdminDatePicker
                      mode="time"
                      value={form.departure_time}
                      onChange={(val: string) =>
                        setForm({ ...form, departure_time: val })
                      }
                    />
                  </FormField>
                </div>
              </>
            )}

            <FormField label="Poznámka">
              <textarea
                value={form.notes}
                onChange={(e) => setForm({ ...form, notes: e.target.value })}
                className="admin-form-textarea"
                rows={3}
              />
            </FormField>

            <div className="admin-form-actions">
              <Link
                to="/attendance/admin"
                className="admin-btn admin-btn-secondary"
              >
                Zrušit
              </Link>
              <button
                type="submit"
                disabled={submitting}
                className="admin-btn admin-btn-primary"
              >
                {submitting ? "Ukládám..." : "Uložit"}
              </button>
            </div>
          </form>
        </div>
      </motion.div>
    </div>
  );
}
