"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useForm } from "@tanstack/react-form";
import { zodValidator } from "@tanstack/zod-form-adapter";
import { z } from "zod";
import { toast } from "sonner";
import useSWR from "swr";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Separator } from "@/components/ui/separator";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import DoctorsService from "@/services/doctors.service";
import AdminDoctorsService from "@/services/admin.doctors.service";
import MediaService from "@/services/media.service";
import type { Doctor, Poli } from "@/types/doctor.type";
import {
  Plus,
  Trash,
  Upload,
  X,
  ChevronDown,
  ChevronUp,
} from "lucide-react";
import { useDropzone } from "react-dropzone";

const DAYS = [
  "Senin",
  "Selasa",
  "Rabu",
  "Kamis",
  "Jumat",
  "Sabtu",
  "Minggu",
];

const doctorSchema = z.object({
  name: z.string().min(1, "Nama dokter wajib diisi"),
  slug: z.string().default(""),
  title: z.string().default(""),
  description: z.string().default(""),
  isOnline: z.boolean().default(true),
  isDirect: z.boolean().default(true),
  poliIds: z.array(z.string()).default([]),
  schedules: z
    .array(
      z.object({
        day: z.string(),
        startTime: z.string(),
        endTime: z.string(),
        isActive: z.boolean().default(true),
      })
    )
    .default([]),
  infoBoxes: z
    .array(
      z.object({
        label: z.string(),
        value: z.string(),
        icon: z.string().default(""),
        order: z.number().default(0),
      })
    )
    .default([]),
});

type DoctorFormData = z.infer<typeof doctorSchema>;

interface DoctorFormProps {
  doctor?: Doctor;
  mode: "create" | "edit";
}

const DoctorForm = ({ doctor, mode }: DoctorFormProps) => {
  const router = useRouter();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [imageUrl, setImageUrl] = useState(doctor?.imageUrl || "");
  const [isUploading, setIsUploading] = useState(false);
  const [newPoliName, setNewPoliName] = useState("");
  const [isCreatingPoli, setIsCreatingPoli] = useState(false);

  const { data: polis = [], mutate: mutatePolis } = useSWR<Poli[]>(
    "/admin/polis",
    () => DoctorsService.getPolis()
  );

  const form = useForm({
    defaultValues: {
      name: doctor?.name || "",
      slug: doctor?.slug || "",
      title: doctor?.title || "",
      description: doctor?.description || "",
      isOnline: doctor?.isOnline ?? true,
      isDirect: doctor?.isDirect ?? true,
      poliIds: doctor?.polis.map((p) => p.id) || [],
      schedules: doctor?.schedules || [],
      infoBoxes: doctor?.infoBoxes || [],
    },
    onSubmit: async ({ value }) => {
      setIsSubmitting(true);
      try {
        const data = {
          ...value,
          imageUrl,
        };

        if (mode === "create") {
          await AdminDoctorsService.create(data);
          toast.success("Dokter berhasil ditambahkan");
        } else if (mode === "edit" && doctor) {
          await AdminDoctorsService.update(doctor.id, data);
          toast.success("Dokter berhasil diperbarui");
        }

        router.push("/admin/doctors");
      } catch (error) {
        toast.error(mode === "create" ? "Gagal menambahkan dokter" : "Gagal memperbarui dokter");
      } finally {
        setIsSubmitting(false);
      }
    },
  });

  // Image upload
  const { getRootProps, getInputProps } = useDropzone({
    accept: {
      "image/*": [".jpeg", ".jpg", ".png", ".webp"],
    },
    maxSize: 5 * 1024 * 1024, // 5MB
    onDrop: async (acceptedFiles) => {
      if (acceptedFiles.length === 0) return;

      setIsUploading(true);
      try {
        const file = acceptedFiles[0];
        const response = await MediaService.upload(file, "doctors");
        if (response) {
          setImageUrl(response.url);
          toast.success("Gambar berhasil diupload");
        }
      } catch (error) {
        toast.error("Gagal mengupload gambar");
      } finally {
        setIsUploading(false);
      }
    },
  });

  // Helper function to generate slug
  const generateSlug = (name: string) => {
    return name
      .toLowerCase()
      .trim()
      .replace(/[^\w\s-]/g, "")
      .replace(/[\s_-]+/g, "-")
      .replace(/^-+|-+$/g, "");
  };

  // Create new poli
  const handleCreatePoli = async () => {
    if (!newPoliName.trim()) return;

    setIsCreatingPoli(true);
    try {
      const newPoli = await AdminDoctorsService.createPoli({
        name: newPoliName,
      });
      await mutatePolis();
      
      // Add new poli to selection
      const currentPoliIds = form.getFieldValue("poliIds");
      form.setFieldValue("poliIds", [...currentPoliIds, newPoli.id]);
      
      setNewPoliName("");
      toast.success("Poli berhasil ditambahkan");
    } catch (error) {
      toast.error("Gagal menambahkan poli");
    } finally {
      setIsCreatingPoli(false);
    }
  };

  // Add schedule
  const addSchedule = () => {
    const current = form.getFieldValue("schedules");
    form.setFieldValue("schedules", [
      ...current,
      { id: crypto.randomUUID(), day: "Senin", startTime: "08:00", endTime: "16:00", isActive: true },
    ]);
  };

  // Remove schedule
  const removeSchedule = (index: number) => {
    const current = form.getFieldValue("schedules");
    form.setFieldValue("schedules", current.filter((_, i) => i !== index));
  };

  // Add info box
  const addInfoBox = () => {
    const current = form.getFieldValue("infoBoxes");
    form.setFieldValue("infoBoxes", [
      ...current,
      { id: crypto.randomUUID(), label: "", value: "", icon: "", order: current.length },
    ]);
  };

  // Remove info box
  const removeInfoBox = (index: number) => {
    const current = form.getFieldValue("infoBoxes");
    form.setFieldValue("infoBoxes", current.filter((_, i) => i !== index));
  };

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        form.handleSubmit();
      }}
      className="space-y-6"
    >
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">
            {mode === "create" ? "Tambah Dokter" : "Edit Dokter"}
          </h1>
          <p className="text-slate-500">
            {mode === "create"
              ? "Tambah data dokter baru"
              : "Perbarui data dokter"}
          </p>
        </div>
        <div className="flex gap-2">
          <Button
            type="button"
            variant="outline"
            onClick={() => router.push("/admin/doctors")}
          >
            Batal
          </Button>
          <Button type="submit" disabled={isSubmitting}>
            {isSubmitting ? "Menyimpan..." : "Simpan"}
          </Button>
        </div>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        {/* Left Column - Basic Info */}
        <div className="space-y-6">
          {/* Basic Info Card */}
          <Card>
            <CardHeader>
              <CardTitle>Informasi Dasar</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* Image Upload */}
              <div className="space-y-2">
                <Label>Foto Dokter</Label>
                <div
                  {...getRootProps()}
                  className="border-2 border-dashed border-slate-300 rounded-lg p-6 text-center cursor-pointer hover:border-primary transition-colors"
                >
                  <input {...getInputProps()} />
                  {imageUrl ? (
                    <div className="flex flex-col items-center gap-2">
                      <Avatar className="h-24 w-24">
                        <AvatarImage src={imageUrl} />
                        <AvatarFallback>DR</AvatarFallback>
                      </Avatar>
                      <p className="text-sm text-slate-500">
                        Klik untuk mengganti foto
                      </p>
                    </div>
                  ) : (
                    <div className="flex flex-col items-center gap-2">
                      <Upload className="h-8 w-8 text-slate-400" />
                      <p className="text-sm text-slate-500">
                        {isUploading
                          ? "Mengupload..."
                          : "Drag & drop atau klik untuk upload"}
                      </p>
                      <p className="text-xs text-slate-400">
                        Maksimal 5MB (JPG, PNG, WebP)
                      </p>
                    </div>
                  )}
                </div>
              </div>

              {/* Name */}
              <form.Field name="name">
                {(field) => (
                  <div className="space-y-2">
                    <Label htmlFor="name">Nama Dokter *</Label>
                    <Input
                      id="name"
                      value={field.state.value}
                      onChange={(e) => field.handleChange(e.target.value)}
                      placeholder="Dr. Nama Dokter"
                    />
                    {field.state.meta.errors && (
                      <p className="text-sm text-red-500">
                        {field.state.meta.errors[0]}
                      </p>
                    )}
                  </div>
                )}
              </form.Field>

              {/* Slug */}
              <form.Field name="slug">
                {(field) => (
                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <Label htmlFor="slug">Slug (URL)</Label>
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={() => {
                          const name = form.getFieldValue("name");
                          if (name) {
                            field.handleChange(generateSlug(name));
                          }
                        }}
                        className="h-auto py-1 px-2 text-xs"
                      >
                        Generate dari nama
                      </Button>
                    </div>
                    <Input
                      id="slug"
                      value={field.state.value}
                      onChange={(e) => field.handleChange(e.target.value)}
                      placeholder="dr-nama-dokter"
                    />
                    <p className="text-xs text-slate-500">
                      Kosongkan untuk generate otomatis dari nama
                    </p>
                  </div>
                )}
              </form.Field>

              {/* Title */}
              <form.Field name="title">
                {(field) => (
                  <div className="space-y-2">
                    <Label htmlFor="title">Gelar/Spesialisasi</Label>
                    <Input
                      id="title"
                      value={field.state.value}
                      onChange={(e) => field.handleChange(e.target.value)}
                      placeholder="Spesialis Anak, Dokter Umum, dll"
                    />
                  </div>
                )}
              </form.Field>

              {/* Description */}
              <form.Field name="description">
                {(field) => (
                  <div className="space-y-2">
                    <Label htmlFor="description">Deskripsi</Label>
                    <Textarea
                      id="description"
                      value={field.state.value}
                      onChange={(e) => field.handleChange(e.target.value)}
                      placeholder="Deskripsi singkat tentang dokter..."
                      rows={4}
                    />
                  </div>
                )}
              </form.Field>
            </CardContent>
          </Card>

          {/* Status Card */}
          <Card>
            <CardHeader>
              <CardTitle>Status</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <form.Field name="isOnline">
                {(field) => (
                  <div className="flex items-center justify-between">
                    <div>
                      <Label className="text-base">Konsultasi Online</Label>
                      <p className="text-sm text-slate-500">
                        Dokter tersedia untuk konsultasi online
                      </p>
                    </div>
                    <Switch
                      checked={field.state.value}
                      onCheckedChange={field.handleChange}
                    />
                  </div>
                )}
              </form.Field>

              <Separator />

              <form.Field name="isDirect">
                {(field) => (
                  <div className="flex items-center justify-between">
                    <div>
                      <Label className="text-base">Temu Langsung</Label>
                      <p className="text-sm text-slate-500">
                        Dokter menerima kunjungan langsung
                      </p>
                    </div>
                    <Switch
                      checked={field.state.value}
                      onCheckedChange={field.handleChange}
                    />
                  </div>
                )}
              </form.Field>
            </CardContent>
          </Card>
        </div>

        {/* Right Column - Poli, Schedules, Info Boxes */}
        <div className="space-y-6">
          {/* Poli Card */}
          <Card>
            <CardHeader>
              <CardTitle>Poli/Spesialisasi</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <form.Field name="poliIds">
                {(field) => (
                  <div className="space-y-2">
                    <Label>Pilih Poli</Label>
                    <div className="flex flex-wrap gap-2">
                      {polis.map((poli) => (
                        <Badge
                          key={poli.id}
                          variant={
                            field.state.value.includes(poli.id)
                              ? "default"
                              : "outline"
                          }
                          className="cursor-pointer"
                          onClick={() => {
                            const current = field.state.value;
                            if (current.includes(poli.id)) {
                              field.handleChange(
                                current.filter((id) => id !== poli.id)
                              );
                            } else {
                              field.handleChange([...current, poli.id]);
                            }
                          }}
                        >
                          {poli.name}
                          {field.state.value.includes(poli.id) && (
                            <X className="h-3 w-3 ml-1" />
                          )}
                        </Badge>
                      ))}
                    </div>
                  </div>
                )}
              </form.Field>

              {/* Add New Poli */}
              <div className="flex gap-2">
                <Input
                  placeholder="Nama poli baru..."
                  value={newPoliName}
                  onChange={(e) => setNewPoliName(e.target.value)}
                />
                <Button
                  type="button"
                  variant="outline"
                  onClick={handleCreatePoli}
                  disabled={isCreatingPoli || !newPoliName.trim()}
                >
                  <Plus className="h-4 w-4" />
                </Button>
              </div>
            </CardContent>
          </Card>

          {/* Schedules Card */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle>Jadwal Praktik</CardTitle>
              <Button type="button" variant="outline" size="sm" onClick={addSchedule}>
                <Plus className="h-4 w-4 mr-2" />
                Tambah
              </Button>
            </CardHeader>
            <CardContent className="space-y-4">
              <form.Field name="schedules">
                {(field) => (
                  <div className="space-y-3">
                    {field.state.value.length === 0 && (
                      <p className="text-sm text-slate-500 text-center py-4">
                        Belum ada jadwal. Klik "Tambah" untuk menambahkan.
                      </p>
                    )}
                    {field.state.value.map((schedule, index) => (
                      <div
                        key={`schedule-${schedule.day}-${index}`}
                        className="flex items-center gap-2 p-3 border rounded-lg"
                      >
                        <Select
                          value={schedule.day}
                          onValueChange={(value) => {
                            if (!value) return;
                            const newSchedules = [...field.state.value];
                            newSchedules[index].day = value;
                            field.handleChange(newSchedules);
                          }}
                        >
                          <SelectTrigger className="w-32">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            {DAYS.map((day) => (
                              <SelectItem key={day} value={day}>
                                {day}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>

                        <Input
                          type="time"
                          value={schedule.startTime}
                          onChange={(e) => {
                            const newSchedules = [...field.state.value];
                            newSchedules[index].startTime = e.target.value;
                            field.handleChange(newSchedules);
                          }}
                          className="w-28"
                        />

                        <span className="text-slate-400">-</span>

                        <Input
                          type="time"
                          value={schedule.endTime}
                          onChange={(e) => {
                            const newSchedules = [...field.state.value];
                            newSchedules[index].endTime = e.target.value;
                            field.handleChange(newSchedules);
                          }}
                          className="w-28"
                        />

                        <Switch
                          checked={schedule.isActive}
                          onCheckedChange={(checked) => {
                            const newSchedules = [...field.state.value];
                            newSchedules[index].isActive = checked;
                            field.handleChange(newSchedules);
                          }}
                        />

                        <Button
                          type="button"
                          variant="ghost"
                          size="icon"
                          onClick={() => removeSchedule(index)}
                        >
                          <Trash className="h-4 w-4 text-red-500" />
                        </Button>
                      </div>
                    ))}
                  </div>
                )}
              </form.Field>
            </CardContent>
          </Card>

          {/* Info Boxes Card */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle>Info Tambahan</CardTitle>
              <Button type="button" variant="outline" size="sm" onClick={addInfoBox}>
                <Plus className="h-4 w-4 mr-2" />
                Tambah
              </Button>
            </CardHeader>
            <CardContent className="space-y-4">
              <form.Field name="infoBoxes">
                {(field) => (
                  <div className="space-y-3">
                    {field.state.value.length === 0 && (
                      <p className="text-sm text-slate-500 text-center py-4">
                        Belum ada info. Klik "Tambah" untuk menambahkan.
                      </p>
                    )}
                    {field.state.value.map((info, index) => (
                      <div
                        key={`info-${info.label}-${index}`}
                        className="flex flex-col gap-2 p-3 border rounded-lg"
                      >
                        <div className="flex-1 grid grid-cols-3 gap-2">
                          <Input
                            placeholder="Label (contoh: Pengalaman)"
                            value={info.label}
                            onChange={(e) => {
                              const newInfoBoxes = [...field.state.value];
                              newInfoBoxes[index].label = e.target.value;
                              field.handleChange(newInfoBoxes);
                            }}
                          />
                          <Input
                            placeholder="Value (contoh: 10+ Tahun)"
                            value={info.value}
                            onChange={(e) => {
                              const newInfoBoxes = [...field.state.value];
                              newInfoBoxes[index].value = e.target.value;
                              field.handleChange(newInfoBoxes);
                            }}
                          />
                          <Input
                            placeholder="Icon (optional)"
                            value={info.icon || ""}
                            onChange={(e) => {
                              const newInfoBoxes = [...field.state.value];
                              newInfoBoxes[index].icon = e.target.value;
                              field.handleChange(newInfoBoxes);
                            }}
                          />
                        </div>

                        <div className="flex items-center gap-1">
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            onClick={() => {
                              if (index === 0) return;
                              const newInfoBoxes = [...field.state.value];
                              const temp = newInfoBoxes[index];
                              newInfoBoxes[index] = newInfoBoxes[index - 1];
                              newInfoBoxes[index - 1] = temp;
                              newInfoBoxes[index].order = index;
                              newInfoBoxes[index - 1].order = index - 1;
                              field.handleChange(newInfoBoxes);
                            }}
                            disabled={index === 0}
                          >
                            <ChevronUp className="h-4 w-4" />
                          </Button>
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            onClick={() => {
                              if (index === field.state.value.length - 1) return;
                              const newInfoBoxes = [...field.state.value];
                              const temp = newInfoBoxes[index];
                              newInfoBoxes[index] = newInfoBoxes[index + 1];
                              newInfoBoxes[index + 1] = temp;
                              newInfoBoxes[index].order = index;
                              newInfoBoxes[index + 1].order = index + 1;
                              field.handleChange(newInfoBoxes);
                            }}
                            disabled={index === field.state.value.length - 1}
                          >
                            <ChevronDown className="h-4 w-4" />
                          </Button>
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            onClick={() => removeInfoBox(index)}
                          >
                            <Trash className="h-4 w-4 text-red-500" />
                          </Button>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </form.Field>
            </CardContent>
          </Card>
        </div>
      </div>
    </form>
  );
};

export default DoctorForm;
