"use client";

import React, { useEffect, useState, useCallback } from "react";
import { Container, Row, Col, Card, Form, FloatingLabel, Badge, Button, Stack, Spinner, ListGroup } from "react-bootstrap";
import { useForm, Controller } from "react-hook-form";
import { useToast } from "@/context/ToastContext";
import { unixToDateTime } from "@/lib/function";
import LoadingCMS from "@/components/LoadingCMS";
import HtmlEditor from "@/components/HtmlEditor";
import { useRecaptcha } from "@/hooks/useRecaptcha";

type LeadReply = {
  sdr_id: number;
  sdr_sd_id: number;
  sdr_subject: string;
  sdr_message: string;
  sdr_date: number;
};

type LeadData = {
  sd_id: number;
  sd_fname: string;
  sd_lname: string;
  sd_email: string;
  sd_mobile: string;
  sd_company: string;
  sd_client_type: string;
  sd_subject: string;
  sd_message: string;
  sd_cloud: number;
  sd_date: number;
  reply_count:number;
  replies: LeadReply[];
};

type MailFormData = {
  sd_id: number;
  subject: string;
  content: string;
};

export default function Leads() {
  const { showToast } = useToast();
  const { getToken } = useRecaptcha();

  const [leads, setLeads] = useState<LeadData[]>([]);
  const [isLoading, setLoading] = useState(true);
  const [searchLead, setLeadSearch] = useState("");
  const [selectedLead, setSelectedLead] = useState<LeadData | null>(null);
  const [fromDate, setFromDate] = useState("");
  const [toDate, setToDate] = useState("");

  const { register, handleSubmit, reset, control, formState: { errors, isSubmitting } } = useForm<MailFormData>({    
    defaultValues: {
      sd_id: 0,
      subject: "",
      content: "",
    }
  });

  const fetchLeads = useCallback(async () => {
    try {
      const res = await fetch("/api/book-demo/list", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
      });
      const json = await res.json();
      if (res.ok && Array.isArray(json.leadsData)) {
        setLeads(json.leadsData);
      }
    } catch {
      showToast("Lead List: Getting failed..", "danger");
    } finally {
      setLoading(false);
    }
  }, [showToast]);

  useEffect(() => {
    fetchLeads();
  }, [fetchLeads]);

  useEffect(() => {
    if (selectedLead) {
      reset();
    }
  }, [selectedLead, reset]);

  const filteredLeads = leads.filter((lead) => {
    const matchesSearch =
      lead.sd_fname?.toLowerCase().includes(searchLead.toLowerCase()) || 
      lead.sd_lname?.toLowerCase().includes(searchLead.toLowerCase()) || 
      lead.sd_company?.toLowerCase().includes(searchLead.toLowerCase()) || 
      lead.sd_client_type?.toLowerCase().includes(searchLead.toLowerCase()) || 
      lead.sd_subject?.toLowerCase().includes(searchLead.toLowerCase()) || 
      lead.sd_message?.toLowerCase().includes(searchLead.toLowerCase()) || 
      lead.sd_email?.toLowerCase().includes(searchLead.toLowerCase()) || 
      lead.sd_mobile?.toLowerCase().includes(searchLead.toLowerCase());
    return matchesSearch;
  });

  const onSubmit = async (data: MailFormData) => {
    try {
      const recaptchaToken = await getToken("reply_lead_save_form");
      const res = await fetch("/api/book-demo/reply", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({...data,recaptchaToken}),
      });
      const result = await res.json();
      if (res.ok) {
        showToast(result.message, "success");
        reset({
          sd_id: 0,
          subject: "",
          content: "",
        });
        setSelectedLead(null);
        fetchLeads();
      }
      else {
        showToast(result.error, "danger");
      }
    } catch {
      showToast("Sending Reply failed.", "danger");
    }
  };

  const downloadExcel = async (filtered = false) => {
    try {
      const res = await fetch("/api/book-demo/export", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ fromDate, toDate }),
      });

      if (!res.ok) throw new Error("Download failed");

      const blob = await res.blob();
      const url = window.URL.createObjectURL(blob);

      const a = document.createElement("a");
      a.href = url;
      a.download = filtered
        ? `leads_${fromDate}_to_${toDate}.xlsx`
        : "leads_all.xlsx";

      a.click();
      window.URL.revokeObjectURL(url);
    } catch {
      showToast("Excel download failed", "danger");
    }
  };


  if (isLoading) return <LoadingCMS />;

  return (
    <Container fluid className="py-3">
      <Row>        
        <Col md={8}>
          <Row xs={1} md={2} className="g-3">
            <Col md={3} className="align-self-center">
              <h1 className="fs-3">Leads <small className="text-body-secondary">({filteredLeads.length})</small></h1>
            </Col>
            <Col md={9}>              
              <Row className="g-3 mb-3">
                <Col md={4}>
                  <FloatingLabel label="Search by keyword..">
                    <Form.Control value={searchLead} onChange={(e) => setLeadSearch(e.target.value)} />
                  </FloatingLabel>
                </Col>
                <Col md={3}>
                  <FloatingLabel label="From Date">
                    <Form.Control
                      type="date"
                      value={fromDate}
                      onChange={(e) => setFromDate(e.target.value)}
                    />
                  </FloatingLabel>
                </Col>
                <Col md={3}>
                  <FloatingLabel label="To Date">
                    <Form.Control
                      type="date"
                      value={toDate}
                      onChange={(e) => setToDate(e.target.value)}
                    />
                  </FloatingLabel>
                </Col>
                <Col md={2} className="d-grid">
                  <Button
                    variant="outline-success"
                    className="rounded-pill"
                    onClick={() => downloadExcel()}
                  >
                    Download
                  </Button>
                </Col>                
              </Row>
            </Col>
            {filteredLeads.map((lead, index) => (
              <Col key={index}>
                <Card className={`h-100 rounded-4 overflow-hidden ${selectedLead && selectedLead.sd_id === lead.sd_id ? 'text-bg-success' : null}`}>
                  <Card.Body>
                    <Card.Title>{lead.sd_fname} {lead.sd_lname}</Card.Title>
                    <Card.Text>{lead.sd_message}</Card.Text>
                  </Card.Body>
                  <ListGroup variant="flush">
                    <ListGroup.Item className="d-flex align-items-center justify-content-between">
                      Lead Type <span className="ms-3">{lead.sd_cloud === 1 ? 'Cloud' : 'Normal'}</span>
                    </ListGroup.Item>
                    <ListGroup.Item className="d-flex align-items-center justify-content-between">
                      Subject <span className="ms-3">{lead.sd_subject}</span>
                    </ListGroup.Item>
                    <ListGroup.Item className="d-flex align-items-center justify-content-between">
                      Client Type <span className="ms-3">{lead.sd_client_type}</span>
                    </ListGroup.Item>
                    <ListGroup.Item className="d-flex align-items-center justify-content-between">
                      Company <span className="ms-3">{lead.sd_company}</span>
                    </ListGroup.Item>
                    <ListGroup.Item className="d-flex align-items-center justify-content-between">
                      Email <span className="ms-3">{lead.sd_email}</span>
                    </ListGroup.Item>
                    <ListGroup.Item className="d-flex align-items-center justify-content-between">
                      Mobile <span className="ms-3">{lead.sd_mobile}</span>
                    </ListGroup.Item>
                    <ListGroup.Item className="d-flex align-items-center justify-content-between">
                      Date <span className="ms-3">{unixToDateTime(lead.sd_date,'date')}</span>
                    </ListGroup.Item>
                  </ListGroup>
                  <Card.Footer className="d-flex align-items-center justify-content-between">
                    {lead.reply_count > 0 ? <Badge bg="primary">{lead.reply_count} Reply Exist</Badge> : <Badge bg="secondary">No Reply</Badge>}
                    <Button variant="outline-danger" className="rounded-pill" onClick={() => { setSelectedLead(lead); reset({sd_id: lead.sd_id, subject: "",content: "",});}}>
                      Send Reply
                    </Button>
                  </Card.Footer>
                </Card>
              </Col>
            ))}
          </Row>
        </Col>
        <Col md={4} className="position-sticky vh-100 overflow-y-auto" style={{ top: "1rem" }}>
          <Card className="rounded-4 bg-light">
            <Card.Body>
              <h2 className="fs-3 mb-4">Create New Reply</h2>
              <Form noValidate onSubmit={handleSubmit(onSubmit)}>
                <Row className="g-3">
                  <Col md={12}>
                    <FloatingLabel label="Mail Subject">
                      <Form.Control type="text"
                        {...register("subject", {
                          required: "Subject is required",
                          minLength: {value: 3,message: "Subject must be at least 3 characters"},
                          maxLength: {value: 150,message: "Subject cannot exceed 150 characters"},
                          validate: (value) => {
                            const cleaned = value.trim();
                            if (!cleaned) {return "Subject is required";}
                            if (!/[A-Za-z0-9]/.test(cleaned)) {return "Subject must contain letters or numbers";}
                            return true;
                          },
                        })} isInvalid={!!errors.subject} />
                      <Form.Control.Feedback type="invalid">
                        {errors.subject?.message}
                      </Form.Control.Feedback>
                    </FloatingLabel>
                  </Col>
                  <Col md={12}>
                    <Controller name="content" control={control} 
                      rules={{
                        validate: (value) => {
                          const cleaned = (value || "").trim();
                          const div = document.createElement("div");
                          div.innerHTML = cleaned;
                          const text = div.textContent?.trim() || "";
                          if (!text) { return "Content is required"; }
                          return true;
                        },
                      }} 
                      render={({ field }) => (
                        <HtmlEditor value={field.value || ""} onChange={field.onChange} />
                      )}
                    />
                    {errors.content && (<div className="invalid-feedback d-block">{errors.content.message}</div>)}                    
                  </Col>
                  {selectedLead && 
                  <Col md={12}>
                    <Stack direction="horizontal" gap={3}>
                      <Button type="submit" variant="danger" className="w-100 rounded-pill" disabled={isSubmitting}>
                        {isSubmitting ? (
                          <Stack gap={2} direction="horizontal">
                            <Spinner animation="grow" size="sm" variant="danger" />
                            <Spinner animation="grow" size="sm" variant="primary" />
                            <Spinner animation="grow" size="sm" variant="success" />
                            <span>Sending...</span>
                          </Stack>
                        ) : "Send"}
                      </Button>
                      <Button variant="outline-secondary" className="w-100 rounded-pill" onClick={() => { reset(); setSelectedLead(null); }} >
                        Cancel
                      </Button>
                    </Stack>
                    {selectedLead.reply_count > 0 ? (
                      <React.Fragment>
                        <h4 className="my-3">Existing Replies</h4>
                        {selectedLead.replies.map((reply, index) => (
                          <Card className="rounded-4 overflow-hidden mb-3" key={index}>
                            <Card.Body>
                              <Card.Title>{reply.sdr_subject}</Card.Title>
                              <div dangerouslySetInnerHTML={{__html:reply.sdr_message}} />
                            </Card.Body>
                            <ListGroup variant="flush">
                              <ListGroup.Item className="d-flex align-items-center justify-content-between">
                                Date <span className="ms-3">{unixToDateTime(reply.sdr_date,'date')}</span>
                              </ListGroup.Item>
                            </ListGroup>
                          </Card>
                        ))}
                      </React.Fragment>
                    ) : (
                      <Card className="rounded-4 overflow-hidden my-3">
                        <Card.Body className="text-center">
                          <Card.Text>No Reply exist yet.</Card.Text>
                        </Card.Body>
                      </Card>
                    )}
                  </Col>}
                </Row>
              </Form>
            </Card.Body>
          </Card>
        </Col>
      </Row>
    </Container>
  );
}
