"use client";

import { useEffect, useState } from "react";
import { useRouter, useParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { RichTextEditor } from "@/components/ui/rich-text-editor";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Loader2, ArrowLeft } from "lucide-react";
import { toast } from "sonner";
import api from "@/lib/api";
import Link from "next/link";
import { PageHeaderSkeleton, SearchableSelect } from "@/components/shared";
import { KENYA_COUNTIES, KENYA_CITIES } from "@/lib/kenya-locations";
import type { Company, CompanyCategory } from "@/lib/types";

export default function EditCompanyPage() {
  const router = useRouter();
  const params = useParams();
  const slug = params.slug as string;
  const [categories, setCategories] = useState<CompanyCategory[]>([]);
  const [loading, setLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [form, setForm] = useState({
    category_id: "",
    name: "",
    short_description: "",
    description: "",
    phone: "",
    email: "",
    website: "",
    address: "",
    city: "",
    county: "",
    meta_title: "",
    meta_description: "",
  });
  const [logo, setLogo] = useState<File | null>(null);
  const [coverImage, setCoverImage] = useState<File | null>(null);
  const [existingLogo, setExistingLogo] = useState<string | null>(null);
  const [existingCover, setExistingCover] = useState<string | null>(null);

  useEffect(() => {
    Promise.all([
      api.get(`/api/companies/${slug}/edit`),
      api.get("/api/companies/categories"),
    ]).then(([companyRes, catRes]) => {
      const company: Company = companyRes.data.data;
      setForm({
        category_id: company.category_id || "",
        name: company.name,
        short_description: company.short_description || "",
        description: company.description || "",
        phone: company.phone || "",
        email: company.email || "",
        website: company.website || "",
        address: company.address || "",
        city: company.city || "",
        county: company.county || "",
        meta_title: company.meta_title || "",
        meta_description: company.meta_description || "",
      });
      setExistingLogo(company.logo_thumbnail || null);
      setExistingCover(company.cover_image || null);
      setCategories(catRes.data.data);
      setLoading(false);
    }).catch(() => {
      toast.error("Failed to load company");
      router.push("/dashboard/companies");
    });
  }, [slug]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    try {
      const formData = new FormData();
      formData.append("_method", "PUT");
      Object.entries(form).forEach(([key, value]) => {
        if (value !== undefined) formData.append(key, value);
      });
      if (logo) formData.append("logo", logo);
      if (coverImage) formData.append("cover_image", coverImage);

      await api.post(`/api/companies/${slug}`, formData, {
        headers: { "Content-Type": "multipart/form-data" },
      });
      toast.success("Company updated successfully");
      router.push("/dashboard/companies");
    } catch (err: any) {
      const message = err.response?.data?.message || "Failed to update company";
      toast.error(message);
    } finally {
      setIsSubmitting(false);
    }
  };

  if (loading) return <PageHeaderSkeleton />;

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="sm" asChild>
          <Link href="/dashboard/companies">
            <ArrowLeft className="mr-2 h-4 w-4" /> Back
          </Link>
        </Button>
        <div>
          <h1 className="font-display text-2xl font-semibold">Edit Company</h1>
          <p className="text-sm text-muted-foreground">Update company listing details</p>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        <div className="grid gap-6 lg:grid-cols-3">
          <Card className="lg:col-span-2">
            <CardHeader>
              <CardTitle className="text-base">Company Information</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid gap-4 sm:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="name">Company Name *</Label>
                  <Input id="name" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="category">Category *</Label>
                  <Select value={form.category_id} onValueChange={(v) => setForm({ ...form, category_id: v })}>
                    <SelectTrigger>
                      <SelectValue placeholder="Select category" />
                    </SelectTrigger>
                    <SelectContent>
                      {categories.map((cat) => (
                        <SelectItem key={cat.id} value={cat.id}>{cat.name}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="short_desc">Short Description</Label>
                <Input id="short_desc" value={form.short_description} onChange={(e) => setForm({ ...form, short_description: e.target.value })} maxLength={500} />
              </div>
              <div className="space-y-2">
                <Label htmlFor="desc">Full Description</Label>
                <RichTextEditor
                  content={form.description}
                  onChange={(html) => setForm({ ...form, description: html })}
                  placeholder="Describe the company..."
                />
              </div>
              <div className="grid gap-4 sm:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="phone">Phone</Label>
                  <Input id="phone" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="email">Email</Label>
                  <Input id="email" type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="website">Website</Label>
                <Input id="website" value={form.website} onChange={(e) => setForm({ ...form, website: e.target.value })} placeholder="https://" />
              </div>
              <div className="space-y-2">
                <Label htmlFor="address">Address</Label>
                <Input id="address" value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} />
              </div>
              <div className="grid gap-4 sm:grid-cols-2">
                <div className="space-y-2">
                  <Label>City</Label>
                  <SearchableSelect
                    options={KENYA_CITIES}
                    value={form.city}
                    onChange={(v) => setForm({ ...form, city: v })}
                    placeholder="Select city"
                    searchPlaceholder="Search cities..."
                    allowCustom
                  />
                </div>
                <div className="space-y-2">
                  <Label>County</Label>
                  <SearchableSelect
                    options={KENYA_COUNTIES}
                    value={form.county}
                    onChange={(v) => setForm({ ...form, county: v })}
                    placeholder="Select county"
                    searchPlaceholder="Search counties..."
                    allowCustom
                  />
                </div>
              </div>
            </CardContent>
          </Card>

          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Media</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="logo">Logo</Label>
                  {logo ? (
                    <img src={URL.createObjectURL(logo)} alt="New logo" className="mb-2 h-16 w-16 rounded-md object-cover" />
                  ) : existingLogo ? (
                    <img src={existingLogo} alt="Current logo" className="mb-2 h-16 w-16 rounded-md object-cover" />
                  ) : null}
                  <Input id="logo" type="file" accept="image/*" onChange={(e) => setLogo(e.target.files?.[0] || null)} />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="cover">Cover Image</Label>
                  {coverImage ? (
                    <img src={URL.createObjectURL(coverImage)} alt="New cover" className="mb-2 h-24 w-full rounded-md object-cover" />
                  ) : existingCover ? (
                    <img src={existingCover} alt="Current cover" className="mb-2 h-24 w-full rounded-md object-cover" />
                  ) : null}
                  <Input id="cover" type="file" accept="image/*" onChange={(e) => setCoverImage(e.target.files?.[0] || null)} />
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-base">SEO</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="meta_title">Meta Title</Label>
                  <Input id="meta_title" value={form.meta_title} onChange={(e) => setForm({ ...form, meta_title: e.target.value })} maxLength={70} />
                  <p className="text-xs text-muted-foreground">{form.meta_title.length}/70</p>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="meta_desc">Meta Description</Label>
                  <Textarea id="meta_desc" value={form.meta_description} onChange={(e) => setForm({ ...form, meta_description: e.target.value })} maxLength={160} rows={3} />
                  <p className="text-xs text-muted-foreground">{form.meta_description.length}/160</p>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>

        <div className="flex justify-end gap-3">
          <Button variant="outline" asChild>
            <Link href="/dashboard/companies">Cancel</Link>
          </Button>
          <Button type="submit" disabled={isSubmitting}>
            {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            Update Company
          </Button>
        </div>
      </form>
    </div>
  );
}
