import { useState } from "react";
import AuthenticatedLayout from "@/layouts/authenticated-layout";
import { Head, Link, useForm } from "@inertiajs/react";
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";

type Institute = {
  id: number;
  name: string;
  type?: string;
  address?: string;
  district?: string;
  upazila?: string;
  division?: string;
  contact_number?: string;
  email?: string;
  website?: string;
  eiin?: string;
  logo?: File | null;
  established_year?: number;
  status: string;
  created_at: string;
  updated_at: string;
  // Added fields to match SQL
  emis_code?: string;
  school_code?: string;
  college_code?: string;
  thana_code?: string;
  description?: string;
};

export default function CreateInstitute() {
  const { data, setData, errors, post, processing } = useForm<Partial<Institute>>({
    name: "",
    type: "",
    address: "",
    district: "",
    upazila: "",
    division: "",
    contact_number: "",
    email: "",
    website: "",
    eiin: "",
    logo: null,
    established_year: undefined,
    status: "1",
    emis_code: "",
    school_code: "",
    college_code: "",
    thana_code: "",
    description: "",
  });

  const [logoPreview, setLogoPreview] = useState<string | null>(null);

  const handleLogoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    setData("logo", file || null);
    if (file) {
      setLogoPreview(URL.createObjectURL(file));
    } else {
      setLogoPreview(null);
    }
  };

  function submit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    // Basic client-side validation
    if (!data.name) {
      alert("Institute Name is required");
      return;
    }
    if (data.email && !/\S+@\S+\.\S+/.test(data.email)) {
      alert("Invalid email format");
      return;
    }
    post(route("institutes.store"), {
      forceFormData: true,
      onSuccess: () => {
        // Reset form or redirect
        setData({
          name: "",
          type: "",
          address: "",
          district: "",
          upazila: "",
          division: "",
          contact_number: "",
          email: "",
          website: "",
          eiin: "",
          logo: null,
          established_year: undefined,
          status: "1",
          emis_code: "",
          school_code: "",
          college_code: "",
          thana_code: "",
          description: "",
        });
        setLogoPreview(null);
      },
    });
  }

  return (
    <AuthenticatedLayout header="Create Institute">
      <Head title="Create Institute" />

      <div className="container mx-auto px-4 py-6 max-w-4xl">
        <div className="flex justify-between items-center mb-6">
          <h1 className="text-2xl font-bold">Create New Institute</h1>
          <Link
            href={route("institutes.index")}
            className="px-4 py-2 bg-gray-200 hover:bg-gray-300 rounded-md transition duration-200"
          >
            Back to Institutes
          </Link>
        </div>

        <Card className="max-w-3xl mx-auto">
          <CardHeader>
            <CardTitle className="text-xl">Institute Information</CardTitle>
            <CardDescription>Fill out the form to register a new institute</CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={submit}>
              <div className="grid gap-4 mb-4">
                {[
                  { id: "name", label: "Institute Name", type: "text", required: true },
                  { id: "type", label: "Type", type: "text" },
                  { id: "address", label: "Address", type: "text" },
                  { id: "district", label: "District", type: "text" },
                  { id: "upazila", label: "Upazila", type: "text" },
                  { id: "division", label: "Division", type: "text" },
                  { id: "contact_number", label: "Contact Number", type: "text" },
                  { id: "email", label: "Email", type: "email" },
                  { id: "website", label: "Website", type: "text" },
                  { id: "eiin", label: "EIIN", type: "text" },
                  { id: "emis_code", label: "EMIS Code", type: "text" },
                  { id: "school_code", label: "School Code", type: "text" },
                  { id: "college_code", label: "College Code", type: "text" },
                  { id: "thana_code", label: "Thana Code", type: "text" },
                  { id: "description", label: "Description", type: "text" },
                ].map(({ id, label, type, required }) => (
                  <div className="grid gap-2" key={id}>
                    <Label htmlFor={id}>{label}</Label>
                    <Input
                      id={id}
                      type={type}
                      value={data[id as keyof Institute] as string || ""}
                      onChange={(e) => setData(id as keyof Institute, e.target.value)}
                      required={required}
                    />
                    {errors[id as keyof typeof errors] && (
                      <div className="text-red-500 text-sm">{errors[id as keyof typeof errors]}</div>
                    )}
                  </div>
                ))}

                <div className="grid gap-2">
                  <Label htmlFor="established_year">Established Year</Label>
                  <Input
                    id="established_year"
                    type="number"
                    value={data.established_year || ""}
                    onChange={(e) => setData("established_year", Number(e.target.value))}
                  />
                  {errors.established_year && (
                    <

div className="text-red-500 text-sm">{errors.established_year}</div>
                  )}
                </div>

                <div className="grid gap-2">
                  <Label htmlFor="status">Status</Label>
                  <select
                    id="status"
                    value={data.status}
                    onChange={(e) => setData("status", e.target.value)}
                    className="border border-gray-300 rounded px-3 py-2"
                  >
                    <option value="1">Active</option>
                    <option value="0">Inactive</option>
                  </select>
                  {errors.status && <div className="text-red-500 text-sm">{errors.status}</div>}
                </div>

                <div className="grid gap-2">
                  <Label htmlFor="logo">Institute Logo</Label>
                  <Input
                    id="logo"
                    type="file"
                    accept="image/*"
                    onChange={handleLogoChange}
                  />
                  {logoPreview && (
                    <img src={logoPreview} alt="Logo Preview" className="mt-2 h-24 w-24 object-cover" />
                  )}
                  {errors.logo && <div className="text-red-500 text-sm">{errors.logo}</div>}
                </div>
              </div>

              <Button type="submit" className="w-full" disabled={processing}>
                {processing ? "Creating..." : "Create Institute"}
              </Button>
            </form>
          </CardContent>
        </Card>
      </div>
    </AuthenticatedLayout>
  );
}