"use client";

import { useState, useEffect } from "react";
import { fetchApi } from "@/lib/api-client";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { ArrowLeft, Save, Globe, Layout, Type } from "lucide-react";
import Link from "next/link";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";

export default function SiteSettings() {
  const [settings, setSettings] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchSettings = async () => {
      try {
        const data = await fetchApi("admin/settings.php");
        setSettings(data);
      } catch (error) {
        console.error("Failed to fetch settings:", error);
      } finally {
        setLoading(false);
      }
    };
    fetchSettings();
  }, []);

  const handleValueChange = (id: string, newValue: string) => {
    setSettings(settings.map(s => s.id === id ? { ...s, value: newValue } : s));
  };

  const handleSaveSetting = async (id: string, value: string) => {
    try {
      await fetchApi("admin/settings.php", {
        method: 'POST',
        body: JSON.stringify({ id, value })
      });
    } catch (error) {
      console.error("Failed to save setting:", error);
    }
  };

  const handleSaveAll = async () => {
    // In a real app, you might want a bulk update endpoint
    for (const setting of settings) {
      await handleSaveSetting(setting.id, setting.value);
    }
    alert("All settings saved successfully!");
  };

  return (
    <div className="container py-10 space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" asChild>
            <Link href="/orchard-v3-panel">
              <ArrowLeft className="h-5 w-5" />
            </Link>
          </Button>
          <div>
            <h1 className="text-3xl font-bold tracking-tight">Site Settings</h1>
            <p className="text-muted-foreground">Manage dynamic site content and global configurations.</p>
          </div>
        </div>
        <Button className="flex items-center gap-2" onClick={handleSaveAll}>
          <Save className="h-4 w-4" /> Save All Changes
        </Button>
      </div>

      <Tabs defaultValue="home" className="space-y-4">
        <TabsList>
          <TabsTrigger value="home" className="flex items-center gap-2">
            <Layout className="h-4 w-4" /> Home Page
          </TabsTrigger>
          <TabsTrigger value="general" className="flex items-center gap-2">
            <Globe className="h-4 w-4" /> General / Footer
          </TabsTrigger>
        </TabsList>

        <TabsContent value="home">
          <Card>
            <CardHeader>
              <CardTitle>Home Page Content</CardTitle>
              <CardDescription>Edit the hero section and landing page text.</CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              {settings.filter(s => s.page === "home").map((setting) => (
                <div key={setting.id} className="space-y-2">
                  <div className="flex items-center gap-2">
                    <Type className="h-4 w-4 text-muted-foreground" />
                    <label className="text-sm font-medium capitalize">{setting.section} {setting.key}</label>
                  </div>
                  {setting.value.length > 50 ? (
                    <Textarea 
                      value={setting.value} 
                      onChange={(e) => handleValueChange(setting.id, e.target.value)}
                      rows={3}
                    />
                  ) : (
                    <Input 
                      value={setting.value} 
                      onChange={(e) => handleValueChange(setting.id, e.target.value)}
                    />
                  )}
                </div>
              ))}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="general">
          <Card>
            <CardHeader>
              <CardTitle>General Settings</CardTitle>
              <CardDescription>Global site elements and footer information.</CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              {settings.filter(s => s.page === "footer").map((setting) => (
                <div key={setting.id} className="space-y-2">
                  <label className="text-sm font-medium capitalize">{setting.section} {setting.key}</label>
                  <Input 
                    value={setting.value} 
                    onChange={(e) => handleValueChange(setting.id, e.target.value)}
                  />
                </div>
              ))}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
