import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Settings, Save, Loader2, RefreshCw, CheckCircle2, XCircle, ArrowDownToLine, ArrowUpFromLine, BookOpen, KeyRound, Building2, Users, Wrench } from "lucide-react";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/components/ui/use-toast";

const SETTINGS_FIELDS = [
  { key: "company_name", label: "Company Name", placeholder: "Your management company name", type: "text" },
  { key: "company_phone", label: "Company Phone", placeholder: "(555) 123-4567", type: "tel" },
  { key: "company_email", label: "Company Email", placeholder: "info@company.com", type: "email" },
  { key: "company_address", label: "Company Address", placeholder: "123 Main St, Suite 100, City, ST 12345", type: "text" },
  { key: "company_website", label: "Website", placeholder: "https://www.company.com", type: "url" },
  { key: "default_timezone", label: "Default Timezone", placeholder: "America/New_York", type: "text" },
];

export default function GeneralSettingsPage() {
  const { toast } = useToast();
  const [settings, setSettings] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [dirty, setDirty] = useState(false);

  useEffect(() => {
    fetchSettings();
  }, []);

  const fetchSettings = async () => {
    setLoading(true);
    const allKeys = [
      ...SETTINGS_FIELDS.map(f => f.key),
      "maintenance_mode",
      "maintenance_message",
    ];
    const { data } = await supabase
      .from("company_settings")
      .select("key, value")
      .in("key", allKeys);

    const map: Record<string, string> = {};
    (data || []).forEach((row: any) => {
      map[row.key] = row.value || "";
    });
    setSettings(map);
    setLoading(false);
    setDirty(false);
  };

  const handleChange = (key: string, value: string) => {
    setSettings(prev => ({ ...prev, [key]: value }));
    setDirty(true);
  };

  const handleSave = async () => {
    setSaving(true);
    const upserts = Object.entries(settings).map(([key, value]) => ({ key, value }));
    const { error } = await supabase.from("company_settings").upsert(upserts, { onConflict: "key" });
    if (error) {
      toast({ title: "Error saving settings", description: error.message, variant: "destructive" });
    } else {
      toast({ title: "Settings saved", description: "Company information has been updated." });
      setDirty(false);
    }
    setSaving(false);
  };

  return (
    <div className="space-y-6 max-w-3xl">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <Settings className="w-6 h-6 text-primary" />
            General Settings
          </h1>
          <p className="text-muted-foreground mt-1">
            Manage your company information and integrations.
          </p>
        </div>
        <Button onClick={handleSave} disabled={saving || !dirty}>
          {saving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Save className="mr-2 h-4 w-4" />}
          Save Changes
        </Button>
      </div>

      {loading ? (
        <div className="flex justify-center py-16">
          <Loader2 className="h-8 w-8 animate-spin text-primary" />
        </div>
      ) : (
        <>
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center gap-2">
                <Wrench className="w-5 h-5 text-primary" />
                Maintenance Mode
              </CardTitle>
              <CardDescription>
                When enabled, only administrators can sign in. Everyone else will be signed out with the message below.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center justify-between rounded-md border p-3">
                <div>
                  <p className="text-sm font-medium">Enable maintenance mode</p>
                  <p className="text-xs text-muted-foreground">Blocks all non-admin sign-ins.</p>
                </div>
                <Switch
                  checked={(settings["maintenance_mode"] || "false").toLowerCase() === "true"}
                  onCheckedChange={(v) => handleChange("maintenance_mode", v ? "true" : "false")}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="maintenance_message">Message shown to non-admin users</Label>
                <Textarea
                  id="maintenance_message"
                  value={settings["maintenance_message"] || ""}
                  onChange={(e) => handleChange("maintenance_message", e.target.value)}
                  placeholder="The site is currently undergoing maintenance. Only administrators can sign in at this time."
                  rows={3}
                />
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle className="text-lg">Company Information</CardTitle>
              <CardDescription>
                This information is used in generated PDFs, email headers, and client-facing documents.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              {SETTINGS_FIELDS.map(field => (
                <div key={field.key} className="space-y-2">
                  <Label htmlFor={field.key}>{field.label}</Label>
                  <Input
                    id={field.key}
                    type={field.type}
                    value={settings[field.key] || ""}
                    onChange={e => handleChange(field.key, e.target.value)}
                    placeholder={field.placeholder}
                  />
                </div>
              ))}
            </CardContent>
          </Card>

        </>
      )}
    </div>
  );
}
